﻿using System;
using System.Collections.Generic;
using System.Linq;
using SAPbouiCOM;
using System.Collections;
using SAPbobsCOM;
using System.Xml;
using System.Text.RegularExpressions;
using BoAddonBiz_FreightForwarder.BusinessBase;

namespace BoAddonBiz_FreightForwarder
{
    /// <summary>
    /// 工具类，用来验证Form中的字段是否为空，或Matrix中是否有不允许为空的空字段
    /// </summary>
    class Utils
    {
        /*供加载ComBobox数据使用*/
        private static SAPbobsCOM.Recordset oRst = SAPBoAddon.B1Addon.B1Addon.SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);

        #region 数据行集合处理
        /// <summary>
        /// 上一条
        /// </summary>
        /// <param name="SBOApp"></param>
        /// <param name="FormUID"></param>
        /// <param name="DataTable"></param>
        public static int Previous(SAPbouiCOM.Application SBOApp, string FormUID, string DataTable)
        {
            SAPbouiCOM.Form oForm = SBOApp.Forms.Item(FormUID);
            if (oForm.Mode == BoFormMode.fm_FIND_MODE)
            {
                throw new Exception("查询状态下不可用。");
            }
            SAPbouiCOM.DBDataSource dbds = oForm.DataSources.DBDataSources.Item(DataTable);
            if (dbds.Offset - 1 >= 0)
                dbds.Offset -= 1;
            else
                SBOApp.SetStatusBarMessage("第一条", SAPbouiCOM.BoMessageTime.bmt_Short, false);
            return dbds.Offset;
        }
        /// <summary>
        /// 下一条
        /// </summary>
        /// <param name="SBOApp"></param>
        /// <param name="FormUID"></param>
        /// <param name="DataTable"></param>
        public static int Next(SAPbouiCOM.Application SBOApp, string FormUID, string DataTable)
        {
            SAPbouiCOM.Form oForm = SBOApp.Forms.Item(FormUID);
            if (oForm.Mode == BoFormMode.fm_FIND_MODE)
            {
                throw new Exception("查询状态下不可用。");
            }
            SAPbouiCOM.DBDataSource dbds = oForm.DataSources.DBDataSources.Item(DataTable);
            if (dbds.Offset + 1 < dbds.Size)
                dbds.Offset += 1;
            else
                SBOApp.SetStatusBarMessage("最后一条", SAPbouiCOM.BoMessageTime.bmt_Short, false);
            return dbds.Offset;
        }
        /// <summary>
        /// 翻页时显示行号,总行号
        /// </summary>
        /// <author>WangPeng</author>
        internal static void ShowDBDSNum(SAPbouiCOM.Form oForm, string DataTableName, int CurrentOffset, string Uds_CargoLine = "CargoLine", string Uds_CargoTotalLine = "CargoTal")
        {
            SAPbouiCOM.DBDataSource dbds = oForm.DataSources.DBDataSources.Item(DataTableName);
            /*Add状态修正Offset  (如果多行Add状态会出现这样的情况 Offset=1,Size=1)*/
            //if (oForm.Mode == BoFormMode.fm_ADD_MODE)
            //{
            //dbds.Offset = 0;
            //}
            dbds.Offset = CurrentOffset;
            oForm.DataSources.UserDataSources.Item(Uds_CargoLine).Value = (dbds.Offset + 1).ToString();
            oForm.DataSources.UserDataSources.Item(Uds_CargoTotalLine).Value = dbds.Size.ToString(); ;
        }
        ///// <summary>
        ///// 控件失去焦点时保存数据
        ///// </summary>
        ///// <param name="SBOApp"></param>
        ///// <param name="FormUID"></param>
        ///// <param name="DataTable"></param>
        ///// <param name="ItemUID"></param>
        //public static void LostFocusSaveDataSource(SAPbouiCOM.Application SBOApp, string FormUID, string DataTable, string ItemUID)
        //{
        //    SAPbouiCOM.Form oForm = SBOApp.Forms.Item(FormUID);
        //    SAPbouiCOM.Item oItem = oForm.Items.Item(ItemUID);
        //    if (oItem.Type == BoFormItemTypes.it_CHECK_BOX
        //        || oItem.Type == BoFormItemTypes.it_COMBO_BOX
        //        || oItem.Type == BoFormItemTypes.it_EDIT
        //        || oItem.Type == BoFormItemTypes.it_EXTEDIT
        //        || oItem.Type == BoFormItemTypes.it_OPTION_BUTTON
        //        || oItem.Type == BoFormItemTypes.it_PANE_COMBO_BOX
        //        || oItem.Type == BoFormItemTypes.it_PICTURE)
        //        if (oItem.Specific.DataBind.TableName == DataTable)
        //        {
        //            SAPbouiCOM.DBDataSource dbds = oForm.DataSources.DBDataSources.Item(DataTable);
        //            dbds.SetValue(oItem.Specific.DataBind.Alias, dbds.Offset, SAPBoAddon.B1Assistant.Item.GetValue(oItem).ToString().Trim());
        //        }
        //}
        /// <summary>
        /// 添加数据到DataSource
        /// </summary>
        /// <param name="SBOApp"></param>
        /// <param name="FormUID"></param>
        /// <param name="DataTable"></param>
        public static int Add(SAPbouiCOM.Application SBOApp, string FormUID, string DataTable)
        {
            SAPbouiCOM.Form oForm = SBOApp.Forms.Item(FormUID);
            if (oForm.Mode == BoFormMode.fm_FIND_MODE)
            {
                throw new Exception("查询状态下不可用。");
            }
            oForm.Items.Item("Down").Visible = false;
            SAPbouiCOM.DBDataSource dbds = oForm.DataSources.DBDataSources.Item(DataTable);
            dbds.InsertRecord(dbds.Size);
            dbds.Offset = dbds.Size - 1;
            return dbds.Offset;
        }
        /// <summary>
        /// 从DataSource中删除数据
        /// </summary>
        /// <param name="SBOApp"></param>
        /// <param name="FormUID"></param>
        /// <param name="DataTable"></param>
        public static int Delete(SAPbouiCOM.Application SBOApp, string FormUID, string DataTable, int Offset)
        {
            SAPbouiCOM.Form oForm = SBOApp.Forms.Item(FormUID);
            if (oForm.Mode == BoFormMode.fm_FIND_MODE)
            {
                throw new Exception("查询状态下不可用。");
            }
            if (oForm.Mode == BoFormMode.fm_OK_MODE)
                oForm.Mode = BoFormMode.fm_UPDATE_MODE;
            SAPbouiCOM.DBDataSource dbds = oForm.DataSources.DBDataSources.Item(DataTable);
            dbds.RemoveRecord(Offset);
            if (dbds.Size - 1 < 0)
                dbds.InsertRecord(dbds.Size);
            dbds.Offset = dbds.Size - 1;
            return dbds.Offset;
        }
        /// <summary>
        /// 浏览所有数据
        /// </summary>
        public static void Survey(SAPbouiCOM.Application SBOApp, SAPbobsCOM.Company SBOCompany, string FormUID, string DataTable)
        {
            SAPbouiCOM.Form oForm = SBOApp.Forms.Item(FormUID);
            if (oForm.Mode == BoFormMode.fm_FIND_MODE)
            {
                throw new Exception("查询状态下不可用。");
            }
            SAPbouiCOM.DBDataSource dbds = oForm.DataSources.DBDataSources.Item(DataTable);
            SAPbouiCOM.Form oChildForm = SAPBoAddon.B1Assistant.Form.LoadToSBOApplciation(System.Windows.Forms.Application.StartupPath + @"\Form\AVA_FF_SurveyForm.srf", "", true);
            SAPbouiCOM.DataTable dt = oChildForm.DataSources.DataTables.Add("dt");
            SAPbobsCOM.Recordset ors = SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);

            #region 设置主了窗体UID
            oForm.DataSources.UserDataSources.Item("ChildUID").Value = oChildForm.UniqueID;
            oChildForm.DataSources.UserDataSources.Item("ParentUID").Value = oForm.UniqueID;
            oChildForm.DataSources.UserDataSources.Item("DataTable").Value = DataTable;
            #endregion

            oChildForm.Freeze(true);
            SBOApp.StatusBar.SetText("正在加载数据...", BoMessageTime.bmt_Long, BoStatusBarMessageType.smt_Warning);
            string SQL = string.Empty;
            string TableName = string.Empty;
            string Alias = string.Empty;
            string Descr = string.Empty;
            string TypeID = string.Empty;
            int Size = 8;
            SAPbouiCOM.BoFieldsType FieldType = default(SAPbouiCOM.BoFieldsType);

            #region 创建数据结构
            foreach (SAPbouiCOM.Item oItem in oForm.Items)
            {
                TableName = GetItemDataTable(oItem);
                if (string.IsNullOrEmpty(TableName) == false)
                {
                    if (TableName == DataTable)
                    {
                        Alias = oItem.Specific.DataBind.Alias;
                        Alias = Alias.Substring(2, Alias.Length - 2);
                        SQL = "SELECT AliasID,Descr,TypeID,SizeID FROM CUFD WHERE TABLEID='" + DataTable + "' And AliasID = '" + Alias + "'";
                        ors.DoQuery(SQL);
                        Alias = ors.Fields.Item("AliasID").Value;
                        Alias = "U_" + Alias;
                        Descr = ors.Fields.Item("Descr").Value;
                        TypeID = ors.Fields.Item("TypeID").Value;
                        Size = ors.Fields.Item("SizeID").Value;
                        switch (TypeID)
                        {
                            case "A":
                                FieldType = BoFieldsType.ft_AlphaNumeric;
                                break;
                            case "B":
                                FieldType = BoFieldsType.ft_Quantity;
                                break;
                            case "D":
                                FieldType = BoFieldsType.ft_Date;
                                break;
                            case "N":
                                FieldType = BoFieldsType.ft_Integer;
                                break;
                            case "M":
                                FieldType = BoFieldsType.ft_Text;
                                break;
                        }
                        dt.Columns.Add(Alias, FieldType, Size);
                        //if (Alias == "U_OrderNumber")
                        //{
                        //    dt.Columns.Add("你大爷", FieldType, Size);
                        //    List<string> s = new List<string>();
                        //    //for (int i = 0; i < dt.Columns.Count; i++)
                        //    //{
                        //    //    s.Add(dt.Columns.Item(i).Name);
                        //    //}
                        //    foreach (SAPbouiCOM.DataColumn oColumn in dt.Columns)//SAP你能再牛逼点么
                        //    {
                        //        s.Add(oColumn.Name);
                        //    }
                        //    bool b = s.Contains(Alias);
                        //}
                    }
                }
            }
            #endregion
            #region 加载数据
            for (int i = 0; i < dbds.Size; i++)
            {
                if (dt.Rows.Count >= 0)
                    dt.Rows.Add(1);
                for (int ii = 0; ii < dt.Columns.Count; ii++)
                {
                    SAPbouiCOM.DataColumn oColumn = dt.Columns.Item(ii);
                    string Value = string.Empty;
                    switch (oColumn.Type)
                    {
                        case BoFieldsType.ft_Integer:
                            if (string.IsNullOrEmpty(dbds.GetValue(oColumn.Name, i).Trim()))
                                Value = "0";
                            else
                                Value = dbds.GetValue(oColumn.Name, i).Trim();
                            break;
                        default:
                            Value = dbds.GetValue(oColumn.Name, i).Trim();
                            break;
                    }
                    dt.SetValue(oColumn.Name, i, Value);
                }
            }
            #endregion
            SAPbouiCOM.Grid oGrid = oChildForm.Items.Item("Grid").Specific as SAPbouiCOM.Grid;
            oGrid.DataTable = dt;
            #region 设置列名
            Dictionary<string, string> fields = Utils.GetFields(SBOCompany, DataTable.Replace("@", ""));
            for (int i = 0; i < oGrid.Columns.Count; i++)
            {
                oGrid.Columns.Item(i).Editable = false;
                Recordset rs = SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
                string combo_table = String.Empty;
                switch (oGrid.Columns.Item(i).TitleObject.Caption)
                {
                    case "U_TransportType":
                    case "U_TransportMode":
                        combo_table = "[@AVA_FF_OMOT]";
                        break;
                    case "U_TrandeMethod":
                        combo_table = "[@AVA_FF_OTRM]";
                        break;
                    case "U_Bargain":
                        combo_table = "[@AVA_FF_BAMD]";
                        break;
                    case "UserSign":
                        combo_table = "[OUSR]";
                        break;
                    case "U_CargoType":
                        combo_table = "[@AVA_FF_CATY]";
                        break;
                    case "U_Currency":
                    case "U_TraCurrency":
                    case "U_ConCurrency":
                    case "U_InvoiceCurrency":
                        combo_table = "[OCRN]";
                        break;
                    case "U_QuantityUnit":
                        combo_table = "[@AVA_FF_OPRI]";
                        break;
                    case "U_SuttleWeightUnit":
                    case "U_GrossWeightUnit":
                    case "U_BillingWeightUnit":
                    case "U_SingleWeightUnit":
                        combo_table = "[@AVA_FF_OPRI]";
                        break;
                    case "U_VolumeUnit":
                        combo_table = "[@AVA_FF_OPRI]";
                        break;
                    case "U_SizeUnit":
                        combo_table = "[@AVA_FF_OPRI]";
                        break;
                    case "U_PackForm":
                        combo_table = "[@AVA_FF_OPCT]";
                        break;
                    default:
                        combo_table = String.Empty;
                        break;
                }
                if (!String.IsNullOrEmpty(combo_table))
                {
                    if (combo_table == "[OUSR]")
                    {
                        //the ComboBoxColumn only accepts string values Message 
                        oGrid.Columns.Item(i).Type = SAPbouiCOM.BoGridColumnType.gct_ComboBox;
                        SAPbouiCOM.ComboBoxColumn cb = oGrid.Columns.Item(i) as SAPbouiCOM.ComboBoxColumn;
                        cb.DisplayType = SAPbouiCOM.BoComboDisplayType.cdt_Description;
                        rs.DoQuery("select USERID,U_NAME,USER_CODE from OUSR Where Locked = 'N'");
                        for (int j = 0; j < rs.RecordCount; j++)
                        {
                            cb.ValidValues.Add(rs.Fields.Item("USERID").Value, rs.Fields.Item("U_Name").Value);
                            rs.MoveNext();
                        }
                    }
                    else if (combo_table == "[OCRN]")
                    {
                        //the ComboBoxColumn only accepts string values Message 
                        oGrid.Columns.Item(i).Type = SAPbouiCOM.BoGridColumnType.gct_ComboBox;
                        SAPbouiCOM.ComboBoxColumn cb = oGrid.Columns.Item(i) as SAPbouiCOM.ComboBoxColumn;
                        cb.DisplayType = SAPbouiCOM.BoComboDisplayType.cdt_Description;
                        rs.DoQuery("select DocCurrCod,CurrName from [OCRN] Where Locked = 'N'");
                        for (int j = 0; j < rs.RecordCount; j++)
                        {
                            cb.ValidValues.Add(rs.Fields.Item("DocCurrCod").Value, rs.Fields.Item("CurrName").Value);
                            rs.MoveNext();
                        }
                    }
                    else
                    {
                        oGrid.Columns.Item(i).Type = SAPbouiCOM.BoGridColumnType.gct_ComboBox;
                        SAPbouiCOM.ComboBoxColumn cb = oGrid.Columns.Item(i) as SAPbouiCOM.ComboBoxColumn;
                        cb.DisplayType = SAPbouiCOM.BoComboDisplayType.cdt_Description;
                        rs.DoQuery("select Code,Name from " + combo_table);
                        for (int j = 0; j < rs.RecordCount; j++)
                        {
                            cb.ValidValues.Add(rs.Fields.Item("Code").Value, rs.Fields.Item("Name").Value);
                            rs.MoveNext();
                        }
                    }
                }
                if (fields.ContainsKey(oGrid.Columns.Item(i).TitleObject.Caption))
                {
                    oGrid.Columns.Item(i).TitleObject.Caption = fields[oGrid.Columns.Item(i).TitleObject.Caption];
                }
            }
            #endregion
            //oGrid.Columns.Item(0).TitleObject.Caption = "单据编号";

            SBOApp.StatusBar.SetText("数据加载完成！", BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Success);
            oChildForm.Freeze(false);
        }
        /// <summary>
        /// 获取Item绑定的表
        /// </summary>
        /// <param name="oItem"></param>
        /// <returns></returns>
        private static string GetItemDataTable(SAPbouiCOM.Item oItem)
        {
            switch (oItem.Type)
            {
                case SAPbouiCOM.BoFormItemTypes.it_EDIT:
                    SAPbouiCOM.EditText oEdit = (SAPbouiCOM.EditText)oItem.Specific;
                    return oEdit.DataBind.TableName;
                case SAPbouiCOM.BoFormItemTypes.it_EXTEDIT:
                    SAPbouiCOM.EditText oExEdit = (SAPbouiCOM.EditText)oItem.Specific;
                    return oExEdit.DataBind.TableName;
                case SAPbouiCOM.BoFormItemTypes.it_COMBO_BOX:
                    SAPbouiCOM.ComboBox oComboBox = (SAPbouiCOM.ComboBox)oItem.Specific;
                    return oComboBox.DataBind.TableName;
                case SAPbouiCOM.BoFormItemTypes.it_CHECK_BOX:
                    SAPbouiCOM.CheckBox oCheckBox = (SAPbouiCOM.CheckBox)oItem.Specific;
                    return oCheckBox.DataBind.TableName;
                case SAPbouiCOM.BoFormItemTypes.it_OPTION_BUTTON:
                    SAPbouiCOM.OptionBtn oOptionBtn = (SAPbouiCOM.OptionBtn)oItem.Specific;
                    return oOptionBtn.DataBind.TableName;
                case SAPbouiCOM.BoFormItemTypes.it_PANE_COMBO_BOX:
                    SAPbouiCOM.PaneComboBox oPaneComboBox = (SAPbouiCOM.PaneComboBox)oItem.Specific;
                    return oPaneComboBox.DataBind.TableName;
                case SAPbouiCOM.BoFormItemTypes.it_PICTURE:
                    SAPbouiCOM.PictureBox oPictureBox = (SAPbouiCOM.PictureBox)oItem.Specific;
                    return oPictureBox.DataBind.TableName;
                default:
                    return null;
            }

        }
        #endregion
        #region 报价、费用方案复制费用条件模板
        /// <summary>
        /// 复制费用条件模板
        /// </summary>
        /// <param name="oForm">窗体</param>
        /// <param name="MatrixUID"></param>
        /// <param name="DataTable"></param>
        /// <param name="ParentLineId"></param>
        /// <param name="FeeCode"></param>
        public static void CopyConditionTemplate(SAPbouiCOM.Form oForm, string MatrixUID, string DataTable, string ParentLineId, string FeeCode)
        {
            SAPbouiCOM.Matrix oMtx = oForm.Items.Item(MatrixUID).Specific;
            SAPbouiCOM.DBDataSource dbds = oForm.DataSources.DBDataSources.Item(DataTable);

            SAPbobsCOM.Recordset rs = SAPBoAddon.B1Addon.B1Addon.SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
            string SQL = @"SELECT U_Condition,U_Value,U_Currency,U_Rate,U_Price,U_VirPrice,U_Unit,T1.U_Remarks
                                        FROM [@AVA_FF_OFCT] T0
	                                        INNER JOIN [@AVA_FF_FCT1] T1 ON T0.DocEntry = T1.DocEntry
                                        Where T0.U_FeeCode = '{0}'";
            rs.DoQuery(string.Format(SQL, FeeCode));
            //判断是否使用费用条件模板中的数据
            if (rs.RecordCount > 0)
            {
                if (SAPBoAddon.B1Addon.B1Addon.SBOApp.MessageBox("此费用项存在条件模板，是否使用条件模板？", 1, "是", "否") == 2)
                {
                    return;
                }
            }
            for (int i = 0; i < rs.RecordCount; i++)
            {
                #region 判断是否存在空行
                string Lineid = string.Empty;
                if (string.IsNullOrEmpty(dbds.GetValue("U_Condition", dbds.Size - 1).Trim()))
                {
                    if (dbds.GetValue("U_LineId", dbds.Size - 1).Trim() != ParentLineId)
                    {
                        dbds.RemoveRecord(dbds.Size - 1);
                        Lineid = SAPBoAddon.B1Assistant.DBDataSource.AddNewRecordTo(dbds, 1, "LineId", "VisOrder").ToString();
                    }
                    else
                    {
                        Lineid = dbds.Size.ToString();

                    }
                    int MatrixRow = SAPBoAddon.B1Assistant.Matrix.GetMatrixRow(oMtx, dbds, "col_f");
                    if (MatrixRow <= 0)
                    {
                        oMtx.AddRow();
                    }
                }
                else
                {
                    Lineid = SAPBoAddon.B1Assistant.DBDataSource.AddNewRecordTo(dbds, 1, "LineId", "VisOrder").ToString();
                    oMtx.AddRow();
                }
                #endregion
                oMtx.GetLineData(oMtx.VisualRowCount);
                dbds.SetValue("LineId", dbds.Offset, Lineid);
                dbds.SetValue("U_LineID", dbds.Offset, ParentLineId);
                dbds.SetValue("U_Condition", dbds.Offset, rs.Fields.Item("U_Condition").Value);
                dbds.SetValue("U_Value", dbds.Offset, rs.Fields.Item("U_Value").Value.ToString());
                dbds.SetValue("U_Currency", dbds.Offset, rs.Fields.Item("U_Currency").Value.ToString());
                dbds.SetValue("U_Rate", dbds.Offset, rs.Fields.Item("U_Rate").Value.ToString());
                dbds.SetValue("U_Price", dbds.Offset, rs.Fields.Item("U_Price").Value.ToString());
                dbds.SetValue("U_VirPrice", dbds.Offset, rs.Fields.Item("U_VirPrice").Value.ToString());
                dbds.SetValue("U_Unit", dbds.Offset, rs.Fields.Item("U_Unit").Value.ToString());
                dbds.SetValue("U_Remarks", dbds.Offset, rs.Fields.Item("U_Remarks").Value.ToString());
                oMtx.SetLineData(oMtx.VisualRowCount);

                rs.MoveNext();
            }
        }
        #endregion
        #region 验证Form/Matrix/DBDS的空值
        /// <summary>
        /// 
        /// </summary>
        /// <param name="B1Form"></param>
        /// <param name="alais_uids">要绑定的字段，和对应的Label的uid</param>
        /// <param name="uid_description">获取焦点的控件uid，和字段显示名称</param>
        /// <returns></returns>
        public static bool CheckFormNullable(Form B1Form, string config, out  KeyValuePair<string, string> uid_description)
        {
            if (String.IsNullOrEmpty(config))
            {
                uid_description = default(KeyValuePair<string, string>);
                return true;
            }
            Dictionary<string, string> alais_uids = new Dictionary<string, string>();
            foreach (string notnull in config.Split(';'))
            {
                alais_uids.Add(notnull.Split(':')[0], notnull.Split(':')[1]);
            }
            foreach (Item item in B1Form.Items)
            {
                if (item.Type == BoFormItemTypes.it_EDIT)
                {
                    EditText edt = item.Specific as EditText;
                    string alias = edt.DataBind.Alias;
                    if (alais_uids.ContainsKey(alias) && edt.DataBind.DataBound)
                    {
                        if (String.IsNullOrEmpty(edt.Value))
                        {
                            string field_description = B1Form.Items.Item(alais_uids[alias]).Specific.Caption;
                            uid_description = new KeyValuePair<string, string>(item.UniqueID, field_description);
                            return false;
                        }
                    }
                }
            }
            uid_description = default(KeyValuePair<string, string>);
            return true;
        }
        #endregion
        #region 初始化ComboBox
        /// <summary>
        /// 将自定义对象填充到ComboBox
        /// </summary>
        /// <param name="company"></param>
        /// <param name="mtx"></param>
        /// <param name="column"></param>
        /// <param name="value"></param>
        /// <param name="description"></param>
        /// <param name="table"></param>
        /// <param name="order"></param>
        public static void InitialMatrixComboBox(SAPbobsCOM.Company company, Matrix mtx, string column, string value, string description, string table, string order = null, string default_value = null, string where = null, bool add_empty = true, bool IsNew = true)
        {
            try
            {
                Recordset rs = company.GetBusinessObject(BoObjectTypes.BoRecordset);
                string select = String.Format("select {0},{1},U_DefaultValue from [{2}]", value, description, table);
                if (String.IsNullOrEmpty(default_value))
                {
                    select = String.Format("select {0},{1} from [{2}]", value, description, table);
                }
                if (!String.IsNullOrEmpty(where))
                {
                    select += String.Format(" where {0} ", where);
                }
                if (!String.IsNullOrEmpty(order))
                {
                    select += String.Format(" order by {0}", order);
                }
                rs.DoQuery(select);
                int select_index = -1;
                if (mtx.Columns.Item(column).Type == BoFormItemTypes.it_COMBO_BOX)
                {
                    for (int i = mtx.Columns.Item(column).ValidValues.Count - 1; i >= 0; i--)
                    {
                        mtx.Columns.Item(column).ValidValues.Remove(i, BoSearchKey.psk_Index);
                    }
                    if (add_empty)
                    {
                        mtx.Columns.Item(column).ValidValues.Add("", "");
                    }
                    for (int i = 0; i < rs.RecordCount; i++)
                    {
                        if (default_value == null || default_value == "")
                        {

                        }
                        else if (default_value == string.Empty)
                        {
                            if (rs.Fields.Item("U_DefaultValue").Value == "Y")
                            {
                                select_index = i;
                            }
                        }
                        else
                        {
                            if (rs.Fields.Item(value).Value.ToString().ToUpper() == default_value.ToUpper())
                            {
                                select_index = i;
                            }
                        }

                        mtx.Columns.Item(column).ValidValues.Add(rs.Fields.Item(value).Value.ToString(), rs.Fields.Item(description).Value.ToString());
                        rs.MoveNext();
                    }
                    if (IsNew)
                        mtx.Columns.Item(column).ValidValues.Add("New", "新建");
                    if (select_index >= 0)
                    {
                        //设置Matrix的动态ValidValues的默认值还不行
                        //ComboBox cb = mtx.Columns.Item(column) as ComboBox;
                        //cb.Select(select_index, BoSearchKey.psk_Index);
                    }
                }
            }
            catch (Exception ex)
            { }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="oCompany"></param>
        /// <param name="oForm"></param>
        /// <param name="MtxUID"></param>
        /// <param name="Row"></param>
        /// <param name="ColUID_Table_Where">分号分隔</param>
        public static void SetMatrixColumnComboBoxDefaultValue(SAPbobsCOM.Company oCompany, Form oForm, string MtxUID, int Row, string[] ColUID_Table_Where)
        {
            SAPbouiCOM.Matrix oMtx;
            SAPbouiCOM.ComboBox oCom;
            SAPbobsCOM.Recordset ors;
            ors = oCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
            oMtx = oForm.Items.Item(MtxUID).Specific;
            if (ColUID_Table_Where == null || ColUID_Table_Where.Length == 0)
            {
                return;
            }
            string column = ColUID_Table_Where[0].Split(':')[0];
            string table = ColUID_Table_Where[0].Split(':')[1];
            string where = ColUID_Table_Where[0].Split(':').Length > 2 ? ColUID_Table_Where[0].Split(':')[2] : null;
            string sql = String.Format("SELECT Top 1 Code,Name,U_DefaultValue,'{0}' as TableName,'{2}' as Col FROM [{0}] Where U_DefaultValue = 'Y' {1}", ColUID_Table_Where[0].Split(':')[1], String.IsNullOrEmpty(where) ? "" : String.Format(" and {0}", where), column);
            for (int i = 1; i < ColUID_Table_Where.Length; i++)
            {
                column = ColUID_Table_Where[i].Split(':')[0];
                table = ColUID_Table_Where[i].Split(':')[1];
                where = ColUID_Table_Where[i].Split(':').Length > 2 ? ColUID_Table_Where[i].Split(':')[2] : null;
                sql += " union all " + String.Format("SELECT Top 1 Code,Name,U_DefaultValue,'{0}' as TableName,'{2}' as Col FROM [{0}] Where U_DefaultValue = 'Y' {1}", ColUID_Table_Where[i].Split(':')[1], String.IsNullOrEmpty(where) ? "" : String.Format(" and {0}", where), column);
            }
            ors.DoQuery(sql);
            for (int i = 0; i < ors.RecordCount; i++)
            {
                string Col = ors.Fields.Item("Col").Value.ToString();
                string TableName = ors.Fields.Item("TableName").Value.ToString();
                string Code = ors.Fields.Item("Code").Value.ToString();
                string config = ColUID_Table_Where.SingleOrDefault(s => s.StartsWith(Col));
                if (!String.IsNullOrEmpty(config))
                {
                    string ColUID = config.Split(':')[0];
                    string Table = config.Split(':')[1];
                    oCom = oMtx.Columns.Item(ColUID).Cells.Item(Row).Specific as SAPbouiCOM.ComboBox;
                    if (oCom != null)
                    {
                        IEnumerator enumerator = oCom.ValidValues.GetEnumerator();
                        if (enumerator != null)
                        {
                            int index = 0;
                            while (enumerator.MoveNext())
                            {
                                if ((enumerator.Current as SAPbouiCOM.ValidValue).Value == Code)
                                {
                                    oCom.Select(index, BoSearchKey.psk_Index);
                                    break;
                                }
                                index++;
                            }
                        }
                    }
                }
                ors.MoveNext();
            }
        }
        /// <summary>
        /// 初始化表头的ComboBox
        /// </summary>
        /// <param name="company"></param>
        /// <param name="item"></param>
        /// <param name="value"></param>
        /// <param name="description"></param>
        /// <param name="table"></param>
        /// <param name="order"></param>
        /// <param name="default_value"></param>
        /// <param name="where"></param>
        /// <param name="add_empty"></param>
        public static void InitialItemComboBox(SAPbobsCOM.Company company, Item item, string value, string description, string table, string order = null, string default_value = null, string where = null, bool add_empty = true, bool IsNew = true, bool clear_before = true)
        {
            try
            {
                Recordset rs = company.GetBusinessObject(BoObjectTypes.BoRecordset);
                string select = String.Format("select {0},{1}{3} from [{2}]", value, description, table, default_value == null ? "" : ",U_DefaultValue");
                if (!String.IsNullOrEmpty(where))
                {
                    select += String.Format(" where {0} ", where);
                }
                if (!String.IsNullOrEmpty(order))
                {
                    select += String.Format(" order by {0}", order);
                }
                rs.DoQuery(select);
                int select_index = -1;
                if (item.Type == BoFormItemTypes.it_COMBO_BOX)
                {
                    ComboBox cb = item.Specific as ComboBox;
                    if (clear_before)
                    {
                        for (int i = cb.ValidValues.Count - 1; i >= 0; i--)
                        {
                            cb.ValidValues.Remove(i, BoSearchKey.psk_Index);
                        }
                    }
                    if (add_empty)
                    {
                        cb.ValidValues.Add("", "");
                    }
                    for (int i = 0; i < rs.RecordCount; i++)
                    {
                        if (default_value == string.Empty)
                        {
                            if (rs.Fields.Item("U_DefaultValue").Value == "Y")
                            {
                                select_index = i;
                            }
                        }
                        else if (!String.IsNullOrEmpty(default_value))
                        {
                            if (rs.Fields.Item(value).Value.ToString().ToUpper() == default_value.ToUpper())
                            {
                                select_index = i;
                            }
                        }
                        string Value = rs.Fields.Item(value).Value;
                        string Description = rs.Fields.Item(description).Value;
                        cb.ValidValues.Add(Value, Description);
                        rs.MoveNext();
                    }
                    if (IsNew)
                        cb.ValidValues.Add("New", "新建");

                    if (select_index >= 0)
                    {
                        cb.Select(select_index + 1, BoSearchKey.psk_Index);
                    }
                }
            }
            catch (Exception ex)
            { }
        }
        /// <summary>
        /// 加载ComboBox，不赋默认值
        /// </summary>
        /// <author>WangPeng</author>
        internal static void ComboBox_InitialItem(SAPbobsCOM.Recordset Rst, Item item, string value, string description, string table, string order = null, string where = null, bool add_empty = true, bool IsNew = true)
        {
            try
            {
                string select = String.Format("select {0},{1} from [{2}]", value, description, table);
                if (!String.IsNullOrEmpty(where))
                {
                    select += String.Format(" {0} ", where);
                }
                if (!String.IsNullOrEmpty(order))
                {
                    select += String.Format(" order by {0}", order);
                }
                if (item.Type == BoFormItemTypes.it_COMBO_BOX)
                {
                    Rst.DoQuery(select);
                    ComboBox cb = item.Specific as ComboBox;
                    if (add_empty)
                    {
                        cb.ValidValues.Add("", "");
                    }
                    for (int i = 0; i < Rst.RecordCount; i++)
                    {
                        string Value = Rst.Fields.Item(0).Value;
                        string Description = Rst.Fields.Item(1).Value;
                        cb.ValidValues.Add(Value, Description);
                        Rst.MoveNext();
                    }
                    if (IsNew)
                    {
                        cb.ValidValues.Add("New", "新建");
                    }

                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// ComboBox选择默认值
        /// </summary>
        /// <author>WangPeng</author>
        internal static string ComboBox_SelectDefault(string Field_Value, string Field_Description, string table, string default_value = "", string where = null)
        {
            try
            {
                if (string.IsNullOrEmpty(default_value))
                {
                    string select = String.Format("SELECT {0},{1} FROM [{2}]  WHERE ISNULL(U_DefaultValue,N'N')=N'Y' ", Field_Value, Field_Description, table);
                    if (!String.IsNullOrEmpty(where))
                    {
                        select += String.Format(" AND {0} ", where);
                    }
                    oRst.DoQuery(select);
                    if (oRst.RecordCount > 0)
                    {
                        default_value = oRst.Fields.Item(Field_Value).Value.Trim();
                    }
                }
                return default_value;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 货物信息相关下拉列表选择默认值
        /// </summary>
        /// <author>WangPeng</author>
        internal static void ComboBox_Cargo_SelectDefault(Form CurrentForm, Dictionary<string, string> Cargo_ComboBoxUID_Field, string TableName_Cargo)
        {
            string DefaultVal = string.Empty;
            string DefaultVal_OCRN = string.Empty;
            string DefaultVal_WeightUnit = string.Empty;
            SAPbouiCOM.DBDataSource dbds_Cargo = CurrentForm.DataSources.DBDataSources.Item(TableName_Cargo);
            //CurrentForm.Freeze(true);
            //try
            //{
            foreach (var item in Cargo_ComboBoxUID_Field)
            {
                switch (item.Value)
                {
                    case "U_CargoType":
                        DefaultVal = Utils.ComboBox_SelectDefault("Code", "Name", "@AVA_FF_CATY");
                        break;
                    case "U_Currency":
                    case "U_TraCurrency":
                    case "U_ConCurrency":
                    case "U_InvoiceCurrency":
                        if (string.IsNullOrEmpty(DefaultVal_OCRN))
                        {
                            DefaultVal_OCRN = Utils.ComboBox_SelectDefault("DocCurrCod", "CurrName", "OCRN");
                        }
                        DefaultVal = DefaultVal_OCRN;
                        break;
                    case "U_QuantityUnit":
                        DefaultVal = Utils.ComboBox_SelectDefault("Code", "Name", "@AVA_FF_OPRI", null, "U_Type = 'Number'");
                        break;
                    case "U_SuttleWeightUnit":
                    case "U_GrossWeightUnit":
                    case "U_BillingWeightUnit":
                    case "U_SingleWeightUnit":
                        if (string.IsNullOrEmpty(DefaultVal_WeightUnit))
                        {
                            DefaultVal_WeightUnit = Utils.ComboBox_SelectDefault("Code", "Name", "@AVA_FF_OPRI", null, "U_Type = 'Weight'");
                        }
                        DefaultVal = DefaultVal_WeightUnit;
                        break;
                    case "U_VolumeUnit":
                        DefaultVal = Utils.ComboBox_SelectDefault("Code", "Name", "@AVA_FF_OPRI", null, "U_Type = 'Volume'");
                        break;
                    case "U_SizeUnit":
                        DefaultVal = Utils.ComboBox_SelectDefault("Code", "Name", "@AVA_FF_OPRI", null, "U_Type = 'Length'");
                        break;
                    case "U_PackForm":
                        DefaultVal = Utils.ComboBox_SelectDefault("Code", "Name", "@AVA_FF_OPCT");
                        break;
                }
                dbds_Cargo.SetValue(item.Value, dbds_Cargo.Offset, DefaultVal);
                DefaultVal = string.Empty;
            }

            //CurrentForm.Refresh();
            //}
            //catch (Exception ex)
            //{
            //    throw ex;
            //}
            //finally
            //{
            //    CurrentForm.Freeze(false);
            //}
        }
        /// <summary>
        /// 添加选中主表默认值
        /// </summary>
        /// <author>WangPeng</author>
        internal static void ComboBox_Main_SelectDefault(SAPbouiCOM.Form CurrentForm, string MainTableName, Dictionary<string, string> MainTable_ComboBoxUID_Field)
        {
            string type = string.Empty;
            if (CurrentForm.TypeEx.Contains("_FF_"))
            {
                type = "Air";
            }
            if (CurrentForm.TypeEx.Contains("_SE_"))
            {
                type = "Sea";
            }
            if (CurrentForm.TypeEx.Contains("_LN_"))
            {
                type = "Land";
            }
            if (CurrentForm.TypeEx.Contains("_OR_"))
            {
                type = "Other";
            }
            string DefaultVal = string.Empty;
            string DefaultVal_WeightUnit = string.Empty;
            SAPbouiCOM.DBDataSource dbds_osod = CurrentForm.DataSources.DBDataSources.Item(MainTableName);//"@AVA_FF_OSOD"
            foreach (var item in MainTable_ComboBoxUID_Field)
            {
                switch (item.Value)
                {
                    case "U_SalesMode":
                        DefaultVal = Utils.ComboBox_SelectDefault("Code", "Name", "@AVA_FF_SALESMODE");//业务方式 
                        dbds_osod.SetValue(item.Value, dbds_osod.Offset, DefaultVal);
                        break;
                    case "U_Currency":
                        DefaultVal = Utils.ComboBox_SelectDefault("DocCurrCod", "CurrName", "OCRN");//费用币种
                        dbds_osod.SetValue(item.Value, dbds_osod.Offset, DefaultVal);
                        break;
                    case "U_TransportType":
                        //根据员工主数据中配置的业务类型的默认方式进行显示 
                        //modifier:Vincent.yin
                        string SQL = string.Empty;
                        int UserID = SAPBoAddon.B1Addon.B1Addon.SBOCompany.UserSignature;
                        SQL = @"SElECT T4.Code
                                                        FROM OUSR T0
	                                                        INNER JOIN OHEM T1 ON T0.UserID = T1.UserID
	                                                        INNER JOIN [@AVA_OHEM] T2 ON T1.U_BusinessType = T2.Code
	                                                        INNER JOIN [@AVA_HEM1] T3 ON T2.Code = T3.Code
	                                                        INNER JOIN [@AVA_FF_OMOT] T4 ON T3.U_BusinessType = T4.Code
                                                        Where  T0.UserID = " + UserID;
                        oRst.DoQuery(SQL);
                        if (oRst.RecordCount <= 0)
                        {
                            DefaultVal = Utils.ComboBox_SelectDefault("Code", "Name", "@AVA_FF_OMOT", null, String.IsNullOrEmpty(type) ? null : String.Format("(U_Type='{0}' or U_Type IS NULL)", type));//运输方式
                        }
                        else
                        {
                            SQL = @"
                                    SElECT T4.Code
                                    FROM OUSR T0
	                                    INNER JOIN OHEM T1 ON T0.UserID = T1.UserID
	                                    INNER JOIN [@AVA_OHEM] T2 ON T1.U_BusinessType = T2.Code
	                                    INNER JOIN [@AVA_HEM1] T3 ON T2.Code = T3.Code
	                                    INNER JOIN [@AVA_FF_OMOT] T4 ON T3.U_BusinessType = T4.Code
                                    Where T3.U_IsDefault = 'Y' And T0.UserID = {0}
                                    ";
                            SQL = string.Format(SQL, UserID);
                            oRst.DoQuery(SQL);
                            if (oRst.RecordCount > 0)
                            {
                                DefaultVal = oRst.Fields.Item(0).Value.ToString();

                            }
                        }
                        dbds_osod.SetValue(item.Value, dbds_osod.Offset, DefaultVal);
                        break;
                    case "U_QuantityUnit":
                        DefaultVal = Utils.ComboBox_SelectDefault("Code", "Name", "@AVA_FF_OPRI", string.Empty, "U_Type = 'Number'");
                        dbds_osod.SetValue(item.Value, dbds_osod.Offset, DefaultVal);
                        break;
                    case "U_GrossWeightUnit":
                    case "U_BillingWeightUnit":
                        if (string.IsNullOrEmpty(DefaultVal_WeightUnit))
                        {
                            DefaultVal_WeightUnit = Utils.ComboBox_SelectDefault("Code", "Name", "@AVA_FF_OPRI", string.Empty, "U_Type = 'Weight'");
                        }
                        DefaultVal = DefaultVal_WeightUnit;
                        dbds_osod.SetValue(item.Value, dbds_osod.Offset, DefaultVal);
                        break;
                    case "U_VolumeUnit":
                        DefaultVal = Utils.ComboBox_SelectDefault("Code", "Name", "@AVA_FF_OPRI", string.Empty, "U_Type = 'Volume'");
                        dbds_osod.SetValue(item.Value, dbds_osod.Offset, DefaultVal);
                        break;
                    case "U_CargoValueUnit":
                        DefaultVal = Utils.ComboBox_SelectDefault("DocCurrCod", "CurrName", "OCRN");
                        dbds_osod.SetValue(item.Value, dbds_osod.Offset, DefaultVal);
                        break;
                    case "U_TrandeMethod"://贸易方式(订单、委托中字段)
                        DefaultVal = Utils.ComboBox_SelectDefault("Code", "Name", "@AVA_FF_OTRM");
                        dbds_osod.SetValue(item.Value, dbds_osod.Offset, DefaultVal);
                        break;
                    case "U_Bargain"://成交方式(订单、委托中字段)
                        DefaultVal = Utils.ComboBox_SelectDefault("Code", "Name", "@AVA_FF_BAMD");
                        dbds_osod.SetValue(item.Value, dbds_osod.Offset, DefaultVal);
                        break;
                }
                DefaultVal = string.Empty;
            }
        }
        /// <summary>
        /// 加载订单、委托、业务单主表的ComboBox
        /// </summary>
        /// <author>WangPeng</author>
        internal static void ComboBox_Main_Initial(SAPbobsCOM.Recordset oRst, SAPbouiCOM.Form CurrentForm, Dictionary<string, string> MainTable_ComboBoxUID_Field)
        {
            string type = string.Empty;
            if (CurrentForm.TypeEx.Contains("_FF_"))
            {
                type = "Air";
            }
            if (CurrentForm.TypeEx.Contains("_SE_"))
            {
                type = "Sea";
            }
            if (CurrentForm.TypeEx.Contains("_LN_"))
            {
                type = "Land";
            }
            if (CurrentForm.TypeEx.Contains("_OR_"))
            {
                type = "Other";
            }
            foreach (var item in MainTable_ComboBoxUID_Field)
            {
                switch (item.Value)
                {
                    case "U_SalesMode":
                        Utils.ComboBox_InitialItem(oRst, CurrentForm.Items.Item(item.Key), "Code", "Name", "@AVA_FF_SALESMODE");//业务方式
                        break;
                    case "U_Currency":
                        Utils.ComboBox_InitialItem(oRst, CurrentForm.Items.Item(item.Key), "DocCurrCod", "CurrName", "OCRN");//费用币种
                        break;
                    case "U_TransportType":
                        //根据员工主数据上配置的此人是否是有什么样的类型进行配置 --Vincent.yin
                        int UserID = SAPBoAddon.B1Addon.B1Addon.SBOCompany.UserSignature;
                        oRst.DoQuery(@"SElECT T4.Code
                                                        FROM OUSR T0
	                                                        INNER JOIN OHEM T1 ON T0.UserID = T1.UserID
	                                                        INNER JOIN [@AVA_OHEM] T2 ON T1.U_BusinessType = T2.Code
	                                                        INNER JOIN [@AVA_HEM1] T3 ON T2.Code = T3.Code
	                                                        INNER JOIN [@AVA_FF_OMOT] T4 ON T3.U_BusinessType = T4.Code
                                                        Where  T0.UserID = " + UserID);
                        if (oRst.RecordCount <= 0)
                        {
                            Utils.ComboBox_InitialItem(oRst, CurrentForm.Items.Item(item.Key), "Code", "Name", "@AVA_FF_OMOT", null, String.IsNullOrEmpty(type) ? null : String.Format("Where U_Type='{0}' or U_Type IS NULL", type), true, false);//运输方式
                        }
                        else
                        {
                            Utils.ComboBox_InitialItem(oRst, CurrentForm.Items.Item(item.Key), "T4.Code", "T4.Name", "OUSR", null, string.Format(@" T0
	                                                                                                                                                                                                                    INNER JOIN OHEM T1 ON T0.UserID = T1.UserID
	                                                                                                                                                                                                                    INNER JOIN [@AVA_OHEM] T2 ON T1.U_BusinessType = T2.Code
	                                                                                                                                                                                                                    INNER JOIN [@AVA_HEM1] T3 ON T2.Code = T3.Code
	                                                                                                                                                                                                                    INNER JOIN [@AVA_FF_OMOT] T4 ON T3.U_BusinessType = T4.Code
                                                                                                                                                                                                                    Where T0.UserID ={0}                                                                                                                                                                                                                     
                                                                                                                                                                                                                    ", UserID), true, false);//运输方式
                        }
                        break;
                    case "U_QuantityUnit":
                        Utils.ComboBox_InitialItem(oRst, CurrentForm.Items.Item(item.Key), "Code", "Name", "@AVA_FF_OPRI", null, " Where U_Type = 'Number'");
                        break;
                    case "U_GrossWeightUnit":
                    case "U_BillingWeightUnit":
                    case "U_SingleWeightUnit":
                        Utils.ComboBox_InitialItem(oRst, CurrentForm.Items.Item(item.Key), "Code", "Name", "@AVA_FF_OPRI", null, " Where U_Type = 'Weight'");
                        break;
                    case "U_VolumeUnit":
                        Utils.ComboBox_InitialItem(oRst, CurrentForm.Items.Item(item.Key), "Code", "Name", "@AVA_FF_OPRI", null, " Where U_Type = 'Volume'");
                        break;
                    case "U_CargoValueUnit":
                        Utils.ComboBox_InitialItem(oRst, CurrentForm.Items.Item(item.Key), "DocCurrCod", "CurrName", "OCRN");
                        break;
                    case "U_TrandeMethod"://贸易方式(订单、委托中字段)
                        Utils.ComboBox_InitialItem(oRst, CurrentForm.Items.Item(item.Key), "Code", "Name", "@AVA_FF_OTRM");
                        break;
                    case "U_Bargain"://成交方式(订单、委托中字段)
                        Utils.ComboBox_InitialItem(oRst, CurrentForm.Items.Item(item.Key), "Code", "Name", "@AVA_FF_BAMD");
                        break;
                }
            }
        }
        #endregion
        #region 获取默认联系人信息
        /// <summary>
        /// 获取指定客户的默认联系人
        /// </summary>
        /// <param name="cardcode"></param>
        /// <returns></returns>
        public static dynamic GetDefaultContractPerson(SAPbobsCOM.Company company, string cardcode)
        {
            Recordset rs = company.GetBusinessObject(BoObjectTypes.BoRecordset);
            //string select = String.Format("select CntctCode,Name,isnull(t0.LastName,'')+isnull(t0.MiddleName,'')+isnull(t0.FirstName,'') as FullName, Cellolar,t0.Fax,t0.E_MailL,t0.Address from OCPR t0 inner join OCRD t1 on t0.CardCode = t1.CardCode and t0.Name = t1.CntctPrsn and t1.CardCode = '{0}'", cardcode);
            string select = String.Format("select CntctCode,Name, Cellolar,t0.Fax,t0.E_MailL,t0.Address,T0.Tel1,T0.Tel2  from OCPR t0 inner join OCRD t1 on t0.CardCode = t1.CardCode and t0.Name = t1.CntctPrsn and t1.CardCode = '{0}'", cardcode);
            rs.DoQuery(select);
            string CntctCode = string.Empty, Name = string.Empty, Cellolar = string.Empty, Fax = string.Empty, Email = string.Empty, Address = string.Empty, FullName = string.Empty, Tel1 = string.Empty, Tel2 = string.Empty, contactWay = string.Empty;

            if (rs.RecordCount > 0)
            {
                CntctCode = rs.Fields.Item("CntctCode").Value.ToString().Trim();
                Name = rs.Fields.Item("Name").Value.ToString().Trim();
                Cellolar = rs.Fields.Item("Cellolar").Value.ToString().Trim();
                Fax = rs.Fields.Item("Fax").Value.ToString().Trim();
                Email = rs.Fields.Item("E_MailL").Value.ToString().Trim();
                Address = rs.Fields.Item("Address").Value.ToString().Trim();
                FullName = rs.Fields.Item("Name").Value.ToString().Trim();//以前的FullName是Last+Middle+First，现在这三个字段被改名移作他用，所以FullName还是取Name
                Tel1 = rs.Fields.Item("Tel1").Value.ToString().Trim();
                Tel2 = rs.Fields.Item("Tel2").Value.ToString().Trim();
            }
            #region 取联系方式
            contactWay = string.IsNullOrEmpty(Tel1) ? Tel2 : Tel1;
            if (string.IsNullOrEmpty(contactWay))
            {
                contactWay = Cellolar;
            }
            #endregion
            return new { CntctCode = CntctCode, Name = Name, FullName = FullName, Cellolar = contactWay, Fax = Fax, Email = Email, Address = Address, Tel1 = Tel1, Tel2 = Tel2 };
        }
        #endregion
        #region 获取业务员
        public static void GetSalesPerson(SAPbouiCOM.DBDataSource dbds, string CardCode)
        {
            /*根据客户带出业务员，2012-05-30 10:27:20临时增加方法，尚未封装*/
            Recordset rs = SAPBoAddon.B1Addon.B1Addon.SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
            rs.DoQuery(String.Format(@"SELECT T1.SlpCode,T1.SlpName
                                                    FROM OCRD T0
	                                                    INNER JOIN OSLP T1 ON T0.SlpCode = T1.SlpCode
                                                    Where CardCode = '{0}'", CardCode));
            if (rs.RecordCount == 1)
            {
                string SlpName = rs.Fields.Item("SlpName").Value;
                string SlpCode = rs.Fields.Item("SlpCode").Value.ToString();
                if (dbds.TableName.EndsWith("OQOT"))//报价单的字段和其他单据字段不一样
                {
                    dbds.SetValue("U_SlpCode", dbds.Offset, SlpName);
                }
                else
                {
                    dbds.SetValue("U_BusinessMan", dbds.Offset, SlpName);
                }
                dbds.SetValue("U_BnsManCode", dbds.Offset, SlpCode);
            }
        }
        #endregion
        #region 系统初始化全局变量
        /// <summary>
        /// 初始化配置信息
        /// </summary>
        /// <param name="app"></param>
        /// <param name="b1form"></param>
        /// <returns></returns>
        public static Dictionary<string, string> InitialConfig(Application app, SAPBoAddon.B1Form b1form)
        {
            Dictionary<string, string> _Configs = null;
            if (_Configs == null)//如果为空
            {
                if (b1form.CurrentForm != null)//如果当前窗体已经存在
                {
                    string xml = b1form.CurrentForm.DataSources.UserDataSources.Item("Config").Value;//从UserDataSource中读取
                    if (xml.Length > 0)
                    {
                        _Configs = B1ResourceManager.GetInstance().DeserializeDictionary(xml);
                    }
                    else
                    {
                        //说明还没有写入UserDataSource
                    }
                }
                if (_Configs == null)//如果还为空，从资源文件里读取
                {
                    Dictionary<string, string> keyvalues = B1ResourceManager.GetInstance().GetResourceKeyValues(b1form.GetType().Name);
                    if (keyvalues.Count == 0)
                    {
                        app.StatusBar.SetText(String.Format("configuration loading failed，the current form may not work properly，please check resource file"), SAPbouiCOM.BoMessageTime.bmt_Medium, SAPbouiCOM.BoStatusBarMessageType.smt_Warning);
                    }
                    _Configs = keyvalues;
                    if (b1form.CurrentForm != null)
                    {
                        b1form.CurrentForm.DataSources.UserDataSources.Item("Config").Value = B1ResourceManager.GetInstance().SerializeDictionary(_Configs);
                    }
                }
            }
            return _Configs;
        }

        #endregion
        #region DBDS/Matrix的验证，删除，复制（行）操作
        /// <summary>
        /// 复制DBDS
        /// </summary>
        /// <param name="source"></param>
        /// <param name="target"></param>
        /// <param name="mapping">Key对应复制到的DBDS，Value对应复制从的DBDS</param>
        /// <param name="main"></param>
        public static void CopyDBDS(DBDataSource source, DBDataSource target, Dictionary<string, Object> initial = null, List<string> filter = null, Dictionary<string, string> mapping = null, bool main = false)
        {
            filter = filter ?? new List<string>();
            List<string> fields_source = Utils.GetDbdsFields(source);
            List<string> fields_target = Utils.GetDbdsFields(target);

            mapping = mapping ?? new Dictionary<string, string>();

            //foreach (var item in mapping)
            //{
            //    if (!fields_target.Contains(item.Key) || !fields_source.Contains(item.Value))
            //    {
            //        mapping.Remove(item.Key);
            //    }
            //}
            foreach (var item in fields_target.Where(s => !filter.Contains(s) && fields_source.Contains(s)))
            {
                if (!mapping.ContainsKey(item))
                {
                    mapping.Add(item, item);
                }
            }
            if (main)
            {
                foreach (var item in mapping)
                {
                    target.SetValue(item.Key, target.Offset, source.GetValue(item.Value, 0));
                }
                if (initial != null)
                {
                    foreach (var item in initial.Where(s => fields_target.Contains(s.Key)))
                    {
                        target.SetValue(item.Key, 0, item.Value.ToString());
                    }
                }
            }
            else
            {
                //这里只复制了同名字段，可以自由扩展
                for (int i = 0; i < source.Size; i++)
                {
                    SAPBoAddon.B1Assistant.DBDataSource.AddNewRecordTo(target, 1, "LineId", "VisOrder");
                    foreach (var item in mapping)
                    {
                        target.SetValue(item.Key, target.Offset, source.GetValue(item.Value, i));
                    }
                    if (initial != null)
                    {
                        foreach (var item in initial.Where(s => fields_target.Contains(s.Key)))
                        {
                            target.SetValue(item.Key, i, item.Value.ToString());
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 删除DBDS中没有值的空行
        /// </summary>
        /// <param name="dbds"></param>
        /// <param name="check"></param>
        public static void RemoveDbdsNoValueLines(SAPbouiCOM.DBDataSource dbds, List<string> check)
        {
            List<string> fields = Utils.GetDbdsFields(dbds, false);
            for (int i = dbds.Size - 1; i >= 0; i--)
            {
                bool allInvalid = true;
                foreach (var item in check)
                {
                    if (dbds.GetValue(item, i).Trim() != "")
                    {
                        allInvalid = false;
                        break;
                    }
                }
                if (allInvalid)
                {
                    dbds.RemoveRecord(i);
                }
            }
        }
        /// <summary>
        /// 删除Matrix中没有值的空行，不同步删除DBDS
        /// </summary>
        /// <param name="mtx"></param>
        /// <param name="check"></param>
        /// <author>Webb.Wen</author>
        /// <create>2012-03-10 14:45:09</create>
        public static void RemoveMatrixNoValueLines(SAPbouiCOM.Matrix mtx, List<string> check)
        {
            IEnumerator enumerator = mtx.Columns.GetEnumerator();
            Dictionary<string, string> Col_Alias = new Dictionary<string, string>();
            while (enumerator.MoveNext())
            {
                Column column = enumerator.Current as Column;
                Col_Alias.Add(column.UniqueID, column.DataBind.DataBound ? column.DataBind.Alias : "");
            }
            for (int i = mtx.RowCount; i >= 1; i--)
            {
                bool allInvalid = true;
                foreach (var item in check)
                {
                    if (Col_Alias.ContainsValue(item))
                    {
                        string alias = Col_Alias.SingleOrDefault(s => s.Value == item).Key;
                        if (SAPBoAddon.B1Assistant.Matrix.GetCellValue(mtx, alias, i) != "")
                        {
                            allInvalid = false;
                            break;
                        }
                    }
                }
                if (allInvalid)
                {
                    mtx.DeleteRow(i);
                }
            }
        }
        /// <summary>
        /// 删除Matrix中没有值的空行（同时删除DBDS）
        /// </summary>
        /// <param name="mtx"></param>
        /// <param name="dbds"></param>
        /// <param name="check"></param>
        /// <param name="keyCol">用来获取DBDS的OffSet</param>
        public static void RemoveMatrixNoValueLines(SAPbouiCOM.Matrix mtx, SAPbouiCOM.DBDataSource dbds, List<string> check, string keyCol)
        {
            List<string> fields = Utils.GetDbdsFields(dbds, false);
            for (int i = mtx.RowCount; i >= 1; i--)
            {
                int offset = SAPBoAddon.B1Assistant.Matrix.GetdbDsOffset(mtx, i, keyCol, dbds);
                dbds.Offset = offset;
                mtx.SetLineData(i);
                bool allInvalid = true;
                foreach (var item in check)
                {
                    if (dbds.GetValue(item, offset).Trim() != "")
                    {
                        allInvalid = false;
                        break;
                    }
                }
                if (allInvalid)
                {
                    dbds.RemoveRecord(offset);
                    mtx.DeleteRow(i);
                }
            }
        }
        /// <summary>
        /// 验证Matrix关键字段对应的值是否为空
        /// </summary>
        /// <param name="mtx"></param>
        /// <param name="row"></param>
        /// <param name="checkFields"></param>
        /// <returns></returns>
        public static List<string> CheckMatrixRow(Matrix mtx, int row, List<string> checkFields)
        {
            List<string> invalid = new List<string>();
            IEnumerator enumerator = mtx.Columns.GetEnumerator();
            while (enumerator.MoveNext())
            {
                Column column = enumerator.Current as Column;
                if (column.DataBind.DataBound && checkFields.Contains(column.DataBind.Alias))
                {
                    if (SAPBoAddon.B1Assistant.Matrix.GetCellValue(mtx, column.UniqueID, row).ToString().Trim() == "")
                    {
                        invalid.Add(column.TitleObject.Caption);
                    }
                }
            }
            return invalid;
        }
        /// <summary>
        ///  验证DBDS关键字段对应的值是否为空
        /// </summary>
        /// <param name="dbds"></param>
        /// <param name="line"></param>
        /// <param name="checkFields"></param>
        /// <returns></returns>
        public static List<string> CheckDbdsLine(DBDataSource dbds, int line, List<string> checkFields)
        {
            List<string> invalid = new List<string>();
            List<string> fields = Utils.GetDbdsFields(dbds);
            foreach (var item in checkFields)
            {
                if (fields.Contains(item))
                {
                    if (dbds.GetValue(item, line).Trim() == "")
                    {
                        invalid.Add(item);
                    }
                }
            }
            return invalid;
        }
        /// <summary>
        /// 复制DBDS行
        /// </summary>
        /// <param name="source"></param>
        /// <param name="line"></param>
        /// <param name="initial"></param>
        /// <param name="VisOrder"></param>
        /// <param name="LineId"></param>
        public static void CopyDbdsLine(DBDataSource source, int line, Dictionary<string, string> initial = null, string VisOrder = "VisOrder", string LineId = "LineId")
        {
            List<string> fields = Utils.GetDbdsFields(source);
            SAPBoAddon.B1Assistant.DBDataSource.AddNewRecordTo(source, 1, LineId, VisOrder);
            foreach (var item in fields)
            {
                if (initial != null && initial.ContainsKey(item))
                {
                    source.SetValue(item, source.Size - 1, initial[item]);
                }
                else
                {
                    source.SetValue(item, source.Size - 1, source.GetValue(item, line));
                }
            }
        }
        /// <summary>
        /// 设置Matrix的行可以编辑（从费用制作类中移至公用）
        /// </summary>
        /// <author>WangPeng</author>
        public static void SetMatrixRowEnable(SAPbouiCOM.Form oForm, string MtxUID)
        {
            SAPbouiCOM.Matrix oMtx;
            oMtx = oForm.Items.Item(MtxUID).Specific;

            for (int RowNum = 1; RowNum <= oMtx.RowCount; RowNum++)
            {
                //oMtx.CommonSetting.SetRowEditable(i, true);
                for (int colIndex = 0; colIndex < oMtx.Columns.Count; colIndex++)
                {
                    if (oMtx.Columns.Item(colIndex).Editable)
                    {
                        oMtx.CommonSetting.SetCellEditable(RowNum, colIndex, true);
                    }
                }
            }
        }
        /// <summary>
        /// 设置Matrix的行不可编辑（从费用制作类中移至公用）
        /// </summary>
        /// <author>WangPeng</author>
        public static void SetMatrixRowDisable(SAPbouiCOM.Form oForm, string MtxUID, string Col_Check, string ColValue)
        {
            SAPbouiCOM.Matrix oMtx;
            oMtx = oForm.Items.Item(MtxUID).Specific;
            for (int i = 1; i <= oMtx.RowCount; i++)
            {
                if (SAPBoAddon.B1Assistant.Matrix.GetCellValue(oMtx, Col_Check, i).ToString() == ColValue)
                {
                    oMtx.CommonSetting.SetRowEditable(i, false);
                }
            }
        }
        #endregion
        #region 键盘快捷键操作
        /// <summary>
        /// 键盘值
        /// </summary>
        public enum BoKeyboardValue { UP = 38, Down = 40 };
        /// <summary>
        /// 键盘快捷键操作
        /// </summary>
        /// <param name="FormUID"></param>
        /// <param name="ItemUID"></param>
        /// <param name="ColUID"></param>
        /// <param name="Row"></param>
        /// <param name="BoKeyValue"></param>
        public static void KeyboardShortcuts(SAPbouiCOM.Form oForm, string ItemUID, string ColUID, int Row, BoKeyboardValue BoKeyValue)
        {
            SAPbouiCOM.Matrix oMtx;

            if (oForm.Items.Item(ItemUID).Type != BoFormItemTypes.it_MATRIX) return;
            oMtx = oForm.Items.Item(ItemUID).Specific;
            switch (BoKeyValue)
            {
                case BoKeyboardValue.Down:
                    if (Row + 1 > oMtx.VisualRowCount) return;
                    oMtx.GetCellSpecific(ColUID, Row + 1).Active = true;
                    break;
                case BoKeyboardValue.UP:
                    if (Row - 1 <= 0) return;
                    oMtx.GetCellSpecific(ColUID, Row - 1).Active = true;
                    break;
            }

        }
        #endregion
        #region 激活子窗体并置前
        /// <summary>
        /// ActiveChildForm的另一个版本，适用于多个子窗体
        /// </summary>
        /// <param name="oForms"></param>
        /// <param name="pVal"></param>
        /// <param name="CurrentForm"></param>
        /// <param name="BubbleEvent"></param>
        public static void ActiveChildForms(SAPbouiCOM.Forms oForms, SAPbouiCOM.ItemEvent pVal, SAPbouiCOM.Form CurrentForm, ref bool BubbleEvent)
        {
            if (pVal.EventType == SAPbouiCOM.BoEventTypes.et_FORM_ACTIVATE
                         || pVal.EventType == SAPbouiCOM.BoEventTypes.et_CLICK
                         || pVal.EventType == SAPbouiCOM.BoEventTypes.et_ITEM_PRESSED)
            {
                for (int i = 0; i < CurrentForm.DataSources.UserDataSources.Count; i++)
                {
                    if (CurrentForm.DataSources.UserDataSources.Item(i).UID == "ChildUID")
                    {
                        if (CurrentForm.DataSources.UserDataSources.Item("ChildUID").Value != "")
                        {
                            foreach (SAPbouiCOM.Form oFormItem in oForms)
                            {
                                if (CurrentForm.DataSources.UserDataSources.Item("ChildUID").Value.Split(';').Contains<string>(oFormItem.UniqueID))//←就改了这里
                                {
                                    SAPbouiCOM.Form ChildForm = oForms.Item(oFormItem.UniqueID);
                                    ChildForm.Select();
                                    if (pVal.ItemUID != "")
                                    {
                                        if (CurrentForm.Items.Item(pVal.ItemUID).Type == SAPbouiCOM.BoFormItemTypes.it_BUTTON) BubbleEvent = false;
                                    }
                                    break;
                                }
                            }
                        }
                        break;
                    }
                }
            }
        }
        /// <summary>
        /// 激动带有子窗体的窗体
        /// </summary>
        /// <param name="pVal"></param>
        public static void ActiveChildForm(SAPbouiCOM.Forms oForms, SAPbouiCOM.ItemEvent pVal, SAPbouiCOM.Form CurrentForm, ref bool BubbleEvent)
        {
            for (int i = 0; i < CurrentForm.DataSources.UserDataSources.Count; i++)
            {
                if (CurrentForm.DataSources.UserDataSources.Item(i).UID == "ChildUID")
                {
                    if (CurrentForm.DataSources.UserDataSources.Item("ChildUID").Value != "")
                    {
                        foreach (SAPbouiCOM.Form oFormItem in oForms)
                        {
                            if (oFormItem.UniqueID == CurrentForm.DataSources.UserDataSources.Item("ChildUID").Value)
                            {
                                SAPbouiCOM.Form ChildForm = oForms.Item(CurrentForm.DataSources.UserDataSources.Item("ChildUID").Value);
                                ChildForm.Select();
                                BubbleEvent = false;
                                //if (pVal.ItemUID != "")
                                //{
                                //    if (CurrentForm.Items.Item(pVal.ItemUID).Type == SAPbouiCOM.BoFormItemTypes.it_BUTTON) BubbleEvent = false;
                                //}
                                break;
                            }
                        }
                    }
                    break;
                }
            }
        }
        /// <summary>
        /// 根据DocEntry值查找窗体对象
        /// </summary>
        /// <param name="oForm"></param>
        /// <param name="DocEntry"></param>
        public static void FindForm(SAPbouiCOM.Form oForm, string DocEntry)
        {
            if (oForm.Mode != SAPbouiCOM.BoFormMode.fm_FIND_MODE)
                oForm.Mode = SAPbouiCOM.BoFormMode.fm_FIND_MODE;
            oForm.Items.Item("3").Enabled = true;
            oForm.Items.Item("3").Specific.Value = DocEntry;
            oForm.Items.Item("1").Click(SAPbouiCOM.BoCellClickType.ct_Collapsed);
        }
        #endregion
        #region 获取指定用户对应的员工
        /// <summary>
        /// 获取指定用户对应的员工
        /// </summary>
        /// <param name="UserID"></param>
        /// <returns></returns>
        public static dynamic GetUserToEmployee(SAPbobsCOM.Company SBOCompany, int UserID)
        {
            SAPbobsCOM.Recordset ors;

            ors = SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
            ors.DoQuery("SELECT Top 1 EmpID,jobTitle AS Name FROM OHEM Where UserID = " + UserID);
            if (ors.RecordCount > 0)
            {
                int EmpID = ors.Fields.Item("EmpID").Value;
                string Name = ors.Fields.Item("Name").Value;
                return new { EmpID = EmpID, Name = Name };
            }
            return new { EmpID = -1, Name = string.Empty };
        }
        #endregion
        #region LinkedButton显示自定义窗体
        /// <summary>
        /// 根据LinkedButton指定的值打开自定义对象窗体
        /// </summary>
        /// <param name="FormUID"></param>
        /// <param name="LinkedButton"></param>
        /// <param name="ObjectCode"></param>
        public static void OpenUserDeFinedObjectForm(SAPbouiCOM.Form oForm, string LinkedButton, string ObjectCode)
        {
            string LinkControl;
            string DocEntry;

            LinkControl = oForm.Items.Item(LinkedButton).LinkTo;
            if (string.IsNullOrEmpty(LinkControl)) return;
            DocEntry = SAPBoAddon.B1Assistant.Item.GetValue(oForm, LinkControl).ToString();
            foreach (var item in DocEntry.Split(','))
            {

                SAPbouiCOM.Form oChildForm = SAPBoAddon.B1Assistant.Form.LoadToSBOApplciation(System.Windows.Forms.Application.StartupPath + @"\Form\" + ObjectCode + @"Form.srf", "");

                oChildForm.Mode = SAPbouiCOM.BoFormMode.fm_FIND_MODE;
                SAPBoAddon.B1Assistant.Item.SetValue(oChildForm, oChildForm.DataBrowser.BrowseBy, item);
                oChildForm.Items.Item("1").Click(SAPbouiCOM.BoCellClickType.ct_Regular);
            }
        }
        /// <summary>
        /// 打开自定义窗体的同名委托
        /// </summary>
        /// <param name="objType"></param>
        /// <param name="docEntry"></param>
        /// <author>Webb.Wen</author>
        /// <create>2012-03-12 12:47:24</create>
        public delegate void ShowFormDelegate(string objType, string docEntry);
        /// <summary>
        /// 打开自定义窗体
        /// </summary>
        /// <param name="oForm">原Form</param>
        /// <param name="LinkedButton">LinkedButton的ID</param>
        /// <param name="ObjectCode">目前对象类型</param>
        /// <param name="showform">打开窗体的委托</param>
        /// <author>Webb.Wen</author>
        /// <create>2012-03-12 12:47:12</create>
        public static void OpenUserDeFinedObjectForm(SAPbouiCOM.Form oForm, string LinkedButton, string ObjectCode, ShowFormDelegate showform)
        {
            string LinkControl;
            string DocEntry;

            LinkControl = oForm.Items.Item(LinkedButton).LinkTo;
            if (string.IsNullOrEmpty(LinkControl)) return;
            DocEntry = SAPBoAddon.B1Assistant.Item.GetValue(oForm, LinkControl).ToString();
            foreach (var item in DocEntry.Split(','))
            {
                SAPbouiCOM.Form oChildForm = SAPBoAddon.B1Assistant.Form.LoadToSBOApplciation(System.Windows.Forms.Application.StartupPath + @"\Form\" + ObjectCode + @"Form.srf", "");
                oChildForm.Mode = SAPbouiCOM.BoFormMode.fm_FIND_MODE;
                SAPBoAddon.B1Assistant.Item.SetValue(oChildForm, oChildForm.DataBrowser.BrowseBy, item);
                oChildForm.Items.Item("1").Click(SAPbouiCOM.BoCellClickType.ct_Regular);
            }
        }
        /// <summary>
        /// 根据MatrixLinkedButton指定的值打开自定义对象窗体
        /// </summary>
        /// <param name="oForm"></param>
        /// <param name="MtxUID"></param>
        /// <param name="ColUID"></param>
        /// <param name="Row"></param>
        /// <param name="ObjectCode"></param>
        public static void OpenUserDeFinedObjectForm(SAPbouiCOM.Form oForm, string MtxUID, string ColUID, int Row, string ObjectCode)
        {
            SAPbouiCOM.Matrix oMtx;
            string DocEntry;

            oMtx = oForm.Items.Item(MtxUID).Specific;

            DocEntry = SAPBoAddon.B1Assistant.Matrix.GetCellValue(oMtx, ColUID, Row).ToString();
            SAPbouiCOM.Form oChildForm = SAPBoAddon.B1Assistant.Form.LoadToSBOApplciation(System.Windows.Forms.Application.StartupPath + @"\Form\" + ObjectCode + @"Form.srf", "");
            oChildForm.Mode = SAPbouiCOM.BoFormMode.fm_FIND_MODE;
            SAPBoAddon.B1Assistant.Item.SetValue(oChildForm, oChildForm.DataBrowser.BrowseBy, DocEntry);
            oChildForm.Items.Item("1").Click(SAPbouiCOM.BoCellClickType.ct_Regular);
        }
        #endregion
        #region  表格上下显示
        ///// <summary>
        ///// 设置数据源的offset
        ///// </summary>
        ///// <param name="ItemUID"></param>
        ///// <param name="Row"></param>
        //internal static void SetOffset_DBDSForDetails(SAPbouiCOM.Form CurrentForm, string MatrixUID, string dbdsTableName, int Row)
        //{
        //    SAPbouiCOM.Matrix omtx = CurrentForm.Items.Item(MatrixUID).Specific;
        //    SAPbouiCOM.DBDataSource dbds = CurrentForm.DataSources.DBDataSources.Item(dbdsTableName);
        //    if (omtx.RowCount >= Row)
        //    {
        //        int cOffset = SAPBoAddon.B1Assistant.Matrix.GetdbDsOffset(omtx, Row, "col_f", dbds);//col_LineId
        //        if (dbds.Offset != cOffset)
        //        {
        //            dbds.Offset = cOffset;
        //        }
        //    }
        //}

        ///// <summary>
        ///// 显示表格行中的数据
        ///// </summary>
        ///// <param name="ColUID"></param>
        ///// <param name="Row"></param>
        //internal static void ShowInfoWithEdit(SAPbouiCOM.Form CurrentForm, string MatrixUID, string dbdsTableName, string ColUID, int Row)
        //{
        //    SAPbouiCOM.Matrix omtx = CurrentForm.Items.Item(MatrixUID).Specific;
        //    SAPbouiCOM.DBDataSource dbds = CurrentForm.DataSources.DBDataSources.Item(dbdsTableName);
        //    SAPbouiCOM.Column oCol = omtx.Columns.Item(ColUID);
        //    if (omtx.RowCount >= Row)
        //    {
        //        string colVal = SAPBoAddon.B1Assistant.Matrix.GetCellValue(omtx, ColUID, Row).ToString().Trim();
        //        dbds.Offset = SAPBoAddon.B1Assistant.Matrix.GetdbDsOffset(omtx, Row, "col_f", dbds);//col_LineId
        //        dbds.SetValue(oCol.DataBind.Alias, dbds.Offset, colVal);
        //    }

        //}

        ///// <summary>
        ///// 将编辑框中数据更新到Matrix中
        ///// </summary>
        ///// <param name="MatrixUID"></param>
        ///// <param name="dbdsTableName"></param>
        //internal static void ShowInfoInMatrix(SAPbouiCOM.Form CurrentForm, string MatrixUID, string dbdsTableName)
        //{
        //    SAPbouiCOM.Matrix omtx = CurrentForm.Items.Item(MatrixUID).Specific;
        //    SAPbouiCOM.DBDataSource dbds = CurrentForm.DataSources.DBDataSources.Item(dbdsTableName);
        //    int matrixRow = SAPBoAddon.B1Assistant.Matrix.GetMatrixRow(omtx, dbds, "col_f");//col_LineId

        //    if (matrixRow > 0)
        //    {
        //        omtx.SetLineData(matrixRow);
        //    }
        //    else
        //    {
        //        SAPBoAddon.B1Addon.B1Addon.SBOApp.StatusBar.SetText("请选中该页签下的表格行操作.", BoMessageTime.bmt_Medium, BoStatusBarMessageType.smt_Warning);
        //    }
        //}
        //internal static void ShowInfoInMatrix(SAPbouiCOM.Form CurrentForm, string MatrixUID, string dbdsTableName, string[] arrayFields)
        //{
        //    CurrentForm.Freeze(true);
        //    try
        //    {
        //        SAPbouiCOM.Matrix omtx = CurrentForm.Items.Item(MatrixUID).Specific;
        //        SAPbouiCOM.DBDataSource dbds = CurrentForm.DataSources.DBDataSources.Item(dbdsTableName);
        //        int matrixRow = SAPBoAddon.B1Assistant.Matrix.GetMatrixRow(omtx, dbds, "col_f");//col_LineId

        //        string[] valInfo = new string[arrayFields.Length];
        //        /*取dbds中显示的值*/
        //        for (int i = 0; i < arrayFields.Length; i++)
        //        {
        //            valInfo[i] = dbds.GetValue(arrayFields[i], dbds.Offset);
        //        }
        //        if (omtx.RowCount <= 0)
        //        {
        //            matrixRow = SAPBoAddon.B1Assistant.Matrix.AutoAddNewLine(CurrentForm, MatrixUID, "col_f", dbdsTableName, -1);
        //        }
        //        /*将matrix中该行的数据刷新到dbds*/
        //        omtx.GetLineData(matrixRow);
        //        /*为显示的值赋值*/
        //        for (int i = 0; i < arrayFields.Length; i++)
        //        {
        //            dbds.SetValue(arrayFields[i], dbds.Offset, valInfo[i]);
        //        }

        //        if (matrixRow > 0)
        //        {
        //            omtx.SetLineData(matrixRow);
        //        }
        //        else
        //        {
        //            SAPBoAddon.B1Addon.B1Addon.SBOApp.StatusBar.SetText("请选中该页签下的表格行操作.", BoMessageTime.bmt_Medium, BoStatusBarMessageType.smt_Warning);
        //        }
        //    }
        //    catch (Exception e)
        //    {
        //        throw e;
        //    }
        //    finally
        //    {
        //        CurrentForm.Freeze(false);
        //    }
        //}
        ///// <summary>
        ///// 累计子表某字段数据
        ///// </summary>
        ///// <param name="CurrentForm"></param>
        ///// <param name="FatherTableName"></param>
        ///// <param name="ChildTableName"></param>
        ///// <param name="FahterFieldName"></param>
        ///// <param name="ChildFieldName"></param>
        //internal static void CalculateTotal(SAPbouiCOM.Form CurrentForm, string FatherTableName, string ChildTableName, string FahterFieldName, string ChildFieldName)
        //{
        //    SAPbouiCOM.DBDataSource dbds_Father = CurrentForm.DataSources.DBDataSources.Item(FatherTableName);
        //    SAPbouiCOM.DBDataSource dbds_Child = CurrentForm.DataSources.DBDataSources.Item(ChildTableName);
        //    decimal LineVal = 0;
        //    decimal TotalVal = 0;
        //    for (int lineIndex = 0; lineIndex < dbds_Child.Size; lineIndex++)
        //    {
        //        LineVal = Convert.ToDecimal(dbds_Child.GetValue(ChildFieldName, lineIndex).ToString().Trim());
        //        TotalVal += LineVal;
        //    }
        //    dbds_Father.SetValue(FahterFieldName, dbds_Father.Offset, TotalVal.ToString());
        //}
        #endregion
        #region 测试验证的高亮显示
        /// <summary>
        /// 
        /// </summary>
        /// <param name="form">要验证的窗体</param>
        /// <param name="dbds"></param>
        /// <param name="mapping">控件UID和对应的DBDS的Field的映射关系</param>
        /// <param name="uid">要验证的控件UID</param>
        /// <param name="regular_color">常规颜色</param>
        /// <param name="warning_color">验证失败的颜色</param>
        internal static KeyValuePair<string, string> ValidItem(Form form, DBDataSource dbds, Dictionary<string, string> mapping, string uid, int regular_color, int warning_color)
        {
            KeyValuePair<string, string> invalid = default(KeyValuePair<string, string>);
            if (mapping.ContainsKey(uid))
            {
                Item item = form.Items.Item(uid);
                if (item.Type == BoFormItemTypes.it_COMBO_BOX || item.Type == BoFormItemTypes.it_EDIT)//目前只验证这两个类型，还有什么类型需要验证再扩展
                {
                    string value = (string)item.Specific.Value;
                    value = value.Trim();//ComboBox会遇到即使没有选中项，值也是空字符串的情况
                    if ((bool)item.Specific.DataBind.DataBound)
                    {
                        BoFieldsType type = (BoFieldsType)dbds.Fields.Item(item.Specific.DataBind.Alias).Type;
                        bool valid = ValidTypeValue(type, value);
                        item.BackColor = valid ? regular_color : warning_color;
                        if (!valid)
                        {
                            invalid = new KeyValuePair<string, string>(uid, mapping[uid]);
                        }
                    }
                }
            }
            return invalid;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="form"></param>
        /// <param name="dbds"></param>
        /// <param name="mapping"></param>
        /// <param name="regular_color"></param>
        /// <param name="warning_color"></param>
        internal static Dictionary<string, string> ValidItems(Form form, DBDataSource dbds, Dictionary<string, string> mapping, int regular_color, int warning_color)
        {
            Dictionary<string, string> invalid = new Dictionary<string, string>();
            foreach (var item in mapping)
            {
                KeyValuePair<string, string> check = ValidItem(form, dbds, mapping, item.Key, regular_color, warning_color);
                if (!String.IsNullOrEmpty(check.Key))
                {
                    invalid.Add(check.Key, check.Value);
                }
            }
            return invalid;
        }
        /// <summary>
        /// 验证字段类型和默认值是否为空（0.0对于字符串不为空，但是对于浮点型也属于空值）
        /// </summary>
        /// <param name="type"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        private static bool ValidTypeValue(BoFieldsType type, string value)
        {
            bool valid = true;
            /*
             *  ft_NotDefined = 0,
                ft_AlphaNumeric = 1,
                ft_Integer = 2,
                ft_Text = 3,
                ft_Date = 4,
                ft_Float = 5,
                ft_ShortNumber = 6,
                ft_Quantity = 7,
                ft_Price = 8,
                ft_Rate = 9,
                ft_Measure = 10,
                ft_Sum = 11,
                ft_Percent = 12,
             */
            switch (type)
            {
                case BoFieldsType.ft_AlphaNumeric:
                case BoFieldsType.ft_Date:
                    valid = !String.IsNullOrEmpty(value);
                    break;
                case BoFieldsType.ft_Integer:
                    valid = !String.IsNullOrEmpty(value) && Convert.ToInt32(value) != 0;
                    break;
                case BoFieldsType.ft_Float:
                    valid = !String.IsNullOrEmpty(value) && Convert.ToSingle(value) != 0.0f;
                    break;
                //需要扩展其它类型的验证再扩展
            }

            return valid;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="form"></param>
        /// <param name="mapping"></param>
        /// <param name="mtx_uid"></param>
        /// <param name="row">非0表示验证指定行，-1表示验证全部行</param>
        /// <param name="regular_color"></param>
        /// <param name="warning_color"></param>
        internal static void ValidMatrix(Form form, DBDataSource dbds, Dictionary<string, string> mapping, string mtx_uid, int row, int regular_color, int warning_color)
        {
            Matrix mtx = form.Items.Item(mtx_uid).Specific;
            if (mtx.VisualRowCount < row)
            {
                return;
            }

            List<int> rows = new List<int>();
            if (row <= 0)
            {
                for (int i = 0; i <= mtx.VisualRowCount; i++)
                {
                    rows.Add(i);
                }
            }
            else
            {
                rows.Add(row);
            }

            foreach (var row_index in rows)
            {
                for (int column_index = 0; column_index < mtx.Columns.Count; column_index++)
                {
                    Column column = mtx.Columns.Item(column_index);
                    if (mapping.ContainsKey(column.UniqueID))
                    {
                        string value = column.Cells.Item(row_index).Specific.Value.ToString().Trim();
                        BoFieldsType type = (BoFieldsType)dbds.Fields.Item(column.DataBind.Alias).Type;
                        bool valid = ValidTypeValue(type, value);
                        mtx.CommonSetting.SetCellBackColor(row_index, column_index, valid ? regular_color : warning_color);
                    }
                }
            }
        }
        #endregion
        #region 设置/获取汇率
        /// <summary>
        /// 根据币种获取汇率
        /// </summary>
        /// <param name="form">窗体</param>
        /// <param name="company">Company</param>
        /// <param name="mtx_uid"></param>
        /// <param name="mtx_currency_col">币种所在的列</param>
        /// <param name="mtx_rate_col">汇率所在的列</param>
        /// <param name="row">指定行</param>
        /// <param name="docdate">关联的时间属性值</param>
        public static void SetRateByCurrency(Form form, SAPbobsCOM.Company company, string mtx_uid, string mtx_currency_col, string mtx_rate_col, int row, string docdate, string ATATDate = null)
        {
            SAPbouiCOM.Matrix oMtx = form.Items.Item(mtx_uid).Specific;
            dynamic Item = oMtx.GetCellSpecific(mtx_currency_col, row);
            string currency = Item.Value;
            SAPbouiCOM.DBDataSource dbds = form.DataSources.DBDataSources.Item(Item.DataBind.TableName);

            DateTime start;
            DateTime end;
            if (string.IsNullOrEmpty(ATATDate))
            {
                DateTime now = new DateTime(Convert.ToInt32(docdate.Substring(0, 4)), Convert.ToInt32(docdate.Substring(4, 2)), Convert.ToInt32(docdate.Substring(6, 2)));
                start = now.AddDays(-now.Day + 1);
                end = now.AddMonths(1).AddDays(-now.Day);
            }
            else
            {
                DateTime Date = DateTime.Parse(ATATDate);
                start = Date.AddDays(-Date.Day + 1);
                end = Date.AddMonths(1).AddDays(-Date.Day);
            }
            double rate = 0.0d;
            if (currency.ToUpper() == "RMB" || currency.ToUpper() == "CNY")
            {
                rate = 1.0d;
            }
            else
            {
                Recordset rs = company.GetBusinessObject(BoObjectTypes.BoRecordset);
                string sql = String.Format("select Rate from ORTT where Currency = '{0}' and RateDate between '{1}' and '{2}'", currency, start.ToString("yyyy-MM-dd"), end.ToString("yyyy-MM-dd"));
                rs.DoQuery(sql);
                if (rs.RecordCount > 0)
                {
                    rate = (double)rs.Fields.Item("Rate").Value;
                }
            }
            dbds.Offset = SAPBoAddon.B1Assistant.Matrix.GetdbDsOffset(oMtx, row, "col_f", dbds);
            oMtx.GetLineData(row);
            dbds.SetValue("U_Rate", dbds.Offset, rate.ToString());
            oMtx.SetLineData(row);
        }
        /// <summary>
        /// 查询当前日期下的汇率
        /// </summary>
        /// <author>WangPeng</author>
        public static decimal GetRateByCurrency(string currency, string DateOfGetRate = null)
        {
            if (String.IsNullOrEmpty(currency))
            {
                return 0;
            }
            if (currency.ToUpper() == "RMB" || currency.ToUpper() == "CNY")
            {
                return 1;
            }
            decimal rate = 0;
            DateTime Date_Rate;
            /*如果给定的取汇率的日期为空则取当天汇率*/
            if (DateOfGetRate == null)
            {
                Date_Rate = DateTime.Now;
            }
            else
            {
                Date_Rate = Convert.ToDateTime(DateOfGetRate);
            }
            //一个月的汇率都是相同的。不需要考虑是哪天的。
            DateTime start = Date_Rate.AddDays(-Date_Rate.Day + 1);
            DateTime end = Date_Rate.AddMonths(1).AddDays(-Date_Rate.Day);

            Recordset rs = SAPBoAddon.B1Addon.B1Addon.SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
            string sql = String.Format("select Rate from ORTT where Currency = '{0}' and RateDate between '{1}' and '{2}' ", currency, start.ToString("yyyy-MM-dd"), end.ToString("yyyy-MM-dd"));
            rs.DoQuery(sql);
            if (rs.RecordCount > 0)
            {
                rate = Convert.ToDecimal(rs.Fields.Item("Rate").Value);
            }
            else
            {
                if (SAPBoAddon.B1Addon.B1Addon.SBOApp.MessageBox("系统中未维护ATD日期的币种汇率，请选择？", 1, "当前汇率", "默认为1") == 1)
                {
                    sql = String.Format("select RateDate, Rate from ORTT where Currency = '{0}' and RateDate =Convert(Date,GetDate())", currency);
                    rs.DoQuery(sql);
                    if (rs.RecordCount > 0)
                    {
                        rate = Convert.ToDecimal(rs.Fields.Item("Rate").Value);
                    }
                }
                else
                {
                    rate = 1;//如果当前汇率没有配置，是返回1还是0？
                }
            }
            return rate;
        }
        #endregion
        #region 订单，委托和业务单的货物操作
        /// <summary>
        /// 新增的重载方法，在统计的时候指定主表的字段和子表的字段的映射关系
        /// </summary>
        /// <param name="form"></param>
        /// <param name="TableName"></param>
        /// <param name="MaterialTableName"></param>
        /// <param name="mapping">主表的字段和子表的字段的映射关系</param>
        /// <author>Webb.Wen</author>
        /// <create>2012-03-26 16:22:21</create>
        public static void MaterialSum(Form form, string TableName, string MaterialTableName, string[] mapping)
        {
            SAPbouiCOM.DBDataSource dbds;
            SAPbouiCOM.DBDataSource dbds_Material;

            try
            {
                form.Freeze(true);
                dbds = form.DataSources.DBDataSources.Item(TableName);
                dbds_Material = form.DataSources.DBDataSources.Item(MaterialTableName);

                foreach (var item in mapping)
                {
                    decimal sum = 0;
                    for (int i = 0; i < dbds_Material.Size; i++)
                    {
                        sum += decimal.Parse(dbds_Material.GetValue(item.Split(':')[1], i).Trim());
                    }
                    dbds.SetValue(item.Split(':')[0], dbds.Offset, sum.ToString());
                }

                form.Freeze(false);
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }
        /// <summary>
        /// 物料合计（要求涉及到合计的字段统一）
        /// </summary>
        /// <param name="form"></param>
        /// <param name="TableName"></param>
        /// <param name="MaterialTableName"></param>
        public static void MaterialSum(Form form, string TableName, string MaterialTableName)
        {
            SAPbouiCOM.DBDataSource dbds;
            SAPbouiCOM.DBDataSource dbds_Material;
            Decimal Quantity = 0, GrossWeight = 0, BillingWeight = 0, Volume = 0, CargoValue = 0;//件数，毛重，计费重，体积，货物价值
            try
            {
                form.Freeze(true);
                dbds = form.DataSources.DBDataSources.Item(TableName);
                dbds_Material = form.DataSources.DBDataSources.Item(MaterialTableName);
                for (int i = 0; i < dbds_Material.Size; i++)
                {
                    Quantity += decimal.Parse(dbds_Material.GetValue("U_Quantity", i).Trim());
                    GrossWeight += decimal.Parse(dbds_Material.GetValue("U_GrossWeight", i).Trim());
                    BillingWeight += decimal.Parse(dbds_Material.GetValue("U_BillingWeight", i).Trim());
                    Volume += decimal.Parse(dbds_Material.GetValue("U_Volume", i).Trim());
                    CargoValue += decimal.Parse(dbds_Material.GetValue("U_CargoValue", i).Trim());
                }
                dbds.SetValue("U_Quantity", dbds.Offset, Quantity.ToString());
                dbds.SetValue("U_GrossWeight", dbds.Offset, GrossWeight.ToString());
                dbds.SetValue("U_BillingWeight", dbds.Offset, BillingWeight.ToString());
                dbds.SetValue("U_Volume", dbds.Offset, Volume.ToString());
                dbds.SetValue("U_CargoValue", dbds.Offset, CargoValue.ToString());
                form.Freeze(false);
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }
        /// <summary>
        /// 同步货物子表和主表统计的单位（只统计第一个货物）
        /// </summary>
        /// <param name="sub"></param>
        /// <param name="subField"></param>
        /// <param name="main"></param>
        /// <param name="mainField"></param>
        /// <author>Webb.Wen</author>
        /// <create>2012-06-14 12:30:36</create>
        internal static void SyncUnit(Form form, string itemUID, DBDataSource sub, DBDataSource main, string mapping = "U_QuantityUnit:U_QuantityUnit;U_GrossWeightUnit:U_GrossWeightUnit;U_BillingWeightUnit:U_BillingWeightUnit;U_InvoiceCurrency:U_CargoValueUnit;U_VolumeUnit:U_VolumeUnit")
        {
            if (mapping != null)
            {
                if (form.Items.Item(itemUID).Type == BoFormItemTypes.it_COMBO_BOX)
                {
                    ComboBox cb = form.Items.Item(itemUID).Specific;
                    if (cb.DataBind.DataBound)
                    {
                        string alias = mapping.Split(';').SingleOrDefault(s => s.Split(':')[0] == cb.DataBind.Alias);
                        if (!string.IsNullOrEmpty(alias))
                        {
                            main.SetValue(alias.Split(':')[1], 0, sub.GetValue(alias.Split(':')[0], 0));
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 初始化涉及到货物的子表迁移到表头的ComboBox
        /// </summary>
        /// <param name="company"></param>
        /// <param name="form"></param>
        /// <param name="Cargo_UID_Field"></param>
        internal static void InitialCargoComboBox(SAPbobsCOM.Company company, Form form, Dictionary<string, string> Cargo_UID_Field)
        {
            form.Freeze(true);
            foreach (var item in Cargo_UID_Field)
            {
                switch (item.Value)
                {
                    case "U_DangerPro":
                        Utils.InitialItemComboBox(company, form.Items.Item(item.Key), "U_DCCode", "U_DCName", "@AVA_FF_ODCM", "U_DCCode", null, null, true, true);
                        break;
                    case "U_CargoType":
                        Utils.InitialItemComboBox(company, form.Items.Item(item.Key), "Code", "Name", "@AVA_FF_CATY", "Code", null, null, true, true);
                        break;
                    case "U_Currency":
                    case "U_TraCurrency":
                    case "U_ConCurrency":
                    case "U_InvoiceCurrency":
                        Utils.InitialItemComboBox(company, form.Items.Item(item.Key), "DocCurrCod", "CurrName", "OCRN", "DocCurrCod", null, null, true, true);
                        break;
                    case "U_QuantityUnit":
                        Utils.InitialItemComboBox(company, form.Items.Item(item.Key), "Code", "Name", "@AVA_FF_OPRI", null, String.Empty, "U_Type = 'Number'", true, true);
                        break;
                    case "U_SuttleWeightUnit":
                    case "U_GrossWeightUnit":
                    case "U_BillingWeightUnit":
                        Utils.InitialItemComboBox(company, form.Items.Item(item.Key), "Code", "Name", "@AVA_FF_OPRI", null, String.Empty, "U_Type = 'Weight'", true, true);
                        break;
                    case "U_VolumeUnit":
                        Utils.InitialItemComboBox(company, form.Items.Item(item.Key), "Code", "Name", "@AVA_FF_OPRI", null, String.Empty, "U_Type = 'Volume'", true, true);
                        break;
                    case "U_SizeUnit":
                        Utils.InitialItemComboBox(company, form.Items.Item(item.Key), "Code", "Name", "@AVA_FF_OPRI", null, String.Empty, "U_Type = 'Length'", true, true);
                        break;
                    case "U_PackForm":
                        Utils.InitialItemComboBox(company, form.Items.Item(item.Key), "Code", "Name", "@AVA_FF_OPCT", null, String.Empty, null, true, true);
                        break;
                }
            }
            form.Freeze(false);
        }
        /// <summary>
        /// 加载Cargo表中ComboBox可选值
        /// </summary>
        /// <author>WangPeng</author>
        internal static void ComboBox_Cargo_Initial(SAPbobsCOM.Recordset Rst, Form form, Dictionary<string, string> Cargo_UID_Field)
        {
            form.Freeze(true);
            foreach (var item in Cargo_UID_Field)
            {
                switch (item.Value)
                {
                    case "U_DangerPro":
                        Utils.ComboBox_InitialItem(Rst, form.Items.Item(item.Key), "U_DCCode", "U_DCName", "@AVA_FF_ODCM");
                        break;
                    case "U_CargoType":
                        Utils.ComboBox_InitialItem(Rst, form.Items.Item(item.Key), "Code", "Name", "@AVA_FF_CATY");
                        break;
                    case "U_Currency":
                    case "U_TraCurrency":
                    case "U_ConCurrency":
                    case "U_InvoiceCurrency":
                        Utils.ComboBox_InitialItem(Rst, form.Items.Item(item.Key), "DocCurrCod", "CurrName", "OCRN");
                        break;
                    case "U_QuantityUnit":
                        Utils.ComboBox_InitialItem(Rst, form.Items.Item(item.Key), "Code", "Name", "@AVA_FF_OPRI", null, " Where U_Type = 'Number'");
                        break;
                    case "U_SuttleWeightUnit":
                    case "U_GrossWeightUnit":
                    case "U_BillingWeightUnit":
                    case "U_SingleWeightUnit":
                        Utils.ComboBox_InitialItem(Rst, form.Items.Item(item.Key), "Code", "Name", "@AVA_FF_OPRI", null, "Where U_Type = 'Weight'");
                        break;
                    case "U_VolumeUnit":
                        Utils.ComboBox_InitialItem(Rst, form.Items.Item(item.Key), "Code", "Name", "@AVA_FF_OPRI", null, "Where U_Type = 'Volume'");
                        break;
                    case "U_SizeUnit":
                        Utils.ComboBox_InitialItem(Rst, form.Items.Item(item.Key), "Code", "Name", "@AVA_FF_OPRI", null, "Where U_Type = 'Length'");
                        break;
                    case "U_PackForm":
                        Utils.ComboBox_InitialItem(Rst, form.Items.Item(item.Key), "Code", "Name", "@AVA_FF_OPCT");
                        break;
                }
            }
            form.Freeze(false);
        }
        #endregion
        #region 分单发货人赋值到公司信息
        /// <summary>
        /// 分单发货人赋值到公司信息
        /// </summary>
        /// <param name="CurrentForm"></param>
        /// <param name="pVal"></param>
        /// <param name="TableName_BpInfo"></param>
        /// <param name="UID_BPMatrix"></param>
        public static void CargoInfoToBpTable(SAPbouiCOM.Form CurrentForm, SAPBoAddon.B1AddonBase.B1ChooseFormList pVal, IssueOrReceipt oIssue_Receipt, string TableName_BpInfo)
        {
            /*公司信息*/
            SAPbouiCOM.DBDataSource dbds_BPInfo = CurrentForm.DataSources.DBDataSources.Item(TableName_BpInfo);
            //SAPbouiCOM.Matrix oMtx_BPInfo = CurrentForm.Items.Item(UID_BPMatrix).Specific;
            string CardCode = Convert.ToString(pVal.SelectedObjects.GetValue("CardCode", 0)).Trim();
            string CareName = Convert.ToString(pVal.SelectedObjects.GetValue("CardName", 0)).Trim();

            dynamic ContactInfo = GetDefaultContractPerson(SAPBoAddon.B1Addon.B1Addon.SBOCompany, CardCode);
            dbds_BPInfo.Offset = 0;
            if (string.IsNullOrEmpty(dbds_BPInfo.GetValue("LineId", dbds_BPInfo.Offset).Trim()))
            {
                dbds_BPInfo.SetValue("LineId", dbds_BPInfo.Offset, (dbds_BPInfo.Offset + 1).ToString());
                dbds_BPInfo.SetValue("VisOrder", dbds_BPInfo.Offset, (dbds_BPInfo.Offset + 1).ToString());
            }
            if (oIssue_Receipt == IssueOrReceipt.Issue)
            {
                dbds_BPInfo.SetValue("U_ConsignorCode", dbds_BPInfo.Offset, CardCode);
                dbds_BPInfo.SetValue("U_ConsignorName", dbds_BPInfo.Offset, CareName);
                if (ContactInfo != null)
                {
                    dbds_BPInfo.SetValue("U_ConsignorContact", dbds_BPInfo.Offset, ContactInfo.FullName);
                    dbds_BPInfo.SetValue("U_Consignorphone", dbds_BPInfo.Offset, ContactInfo.Cellolar);
                    dbds_BPInfo.SetValue("U_ConsignorAddress", dbds_BPInfo.Offset, ContactInfo.Address);
                    dbds_BPInfo.SetValue("U_Consignoremail", dbds_BPInfo.Offset, ContactInfo.Email);
                }
            }
            else if (oIssue_Receipt == IssueOrReceipt.Receipt)
            {
                dbds_BPInfo.SetValue("U_ConsigneeNo", dbds_BPInfo.Offset, CardCode);
                dbds_BPInfo.SetValue("U_ConsigneeName", dbds_BPInfo.Offset, CareName);
                if (ContactInfo != null)
                {
                    dbds_BPInfo.SetValue("U_Deliveryphone", dbds_BPInfo.Offset, ContactInfo.Cellolar);
                    dbds_BPInfo.SetValue("U_DeliveryAddress", dbds_BPInfo.Offset, ContactInfo.Address);
                    dbds_BPInfo.SetValue("U_Deliveryemail", dbds_BPInfo.Offset, ContactInfo.Email);
                    dbds_BPInfo.SetValue("U_DeliveryMan", dbds_BPInfo.Offset, ContactInfo.FullName);
                }
            }
            //oMtx_BPInfo.LoadFromDataSource();
        }
        #endregion
        #region 检查业务伙伴是否为空
        /// <summary>
        /// 检查业务伙伴是否为空
        /// </summary>
        /// <param name="oForm"></param>
        /// <param name="TableName"></param>
        /// <param name="CardName"></param>
        /// <returns></returns>
        public static bool CheckBusinessPartner(SAPbouiCOM.Application SBOApp, SAPbouiCOM.Form oForm, string TableName, string CardName)
        {
            SAPbouiCOM.DBDataSource dbds;
            dbds = oForm.DataSources.DBDataSources.Item(TableName);
            if (string.IsNullOrEmpty(dbds.GetValue("U_CardCode", dbds.Offset).Trim()))
            {
                SBOApp.MessageBox("请重新选择客户，再进行保存", 1, "OK");
                return false;
            }
            if (string.IsNullOrEmpty(dbds.GetValue(CardName, dbds.Offset).Trim()))
            {
                SBOApp.MessageBox("保存时，客户不能为空，请检查后再操作！", 1, "OK");
                return false;
            }
            return true;
        }
        #endregion
        #region 单据的查询
        /// <summary>
        /// 适用于查找窗体的查找
        /// </summary>
        /// <param name="uds_field">映射UserDataSource和DBDS的Field，用来生成select query语句</param>
        /// <param name="select"></param>
        /// <param name="form"></param>
        /// <param name="app"></param>
        /// <param name="company"></param>
        /// <param name="tablename"></param>
        public static int Search(string uds_field, string select, Form form, Application app, SAPbobsCOM.Company company, string tablename)
        {
            List<string> conditions = new List<string>();
            Dictionary<string, BoDataType> uds = Utils.GetUserDataSource(form);
            List<string> tables = new List<string>();
            Regex r = new Regex("(?<=\\[@)\\w+(?=\\])");
            MatchCollection mc = r.Matches(select);
            foreach (Match m in mc)
            {
                tables.Add(m.Value);
            }
            Dictionary<string, string> fields = Utils.GetFields(company, tables);
            fields.Add("UserSign", "创建人");
            XmlDocument xml = new XmlDocument();
            xml.LoadXml(form.GetAsXML());
            XmlNodeList nodes = xml.ChildNodes[1].SelectNodes(String.Format("//item/specific/databind[@databound='1']"));
            foreach (XmlNode node in nodes)
            {
                string uid = node.ParentNode.ParentNode.Attributes["uid"].Value;
                if (node.Attributes["alias"] == null)
                    continue;
                string alias = node.Attributes["alias"].Value;
                string table = node.Attributes["table"].Value;
                if (!fields.ContainsKey(alias) && !uds.ContainsKey(alias))
                {
                    continue;
                }
                if (table == tablename)//DBDS里取值
                {
                    if (fields.ContainsKey(alias))
                    {
                        string value = form.DataSources.DBDataSources.Item(tablename).GetValue(alias, 0).Trim();
                        if (value.Length > 0)
                        {
                            conditions.Add(String.Format("{0} like '%{1}%'", alias, value));
                        }
                    }
                }
                else
                {
                    if (uds.ContainsKey(alias))
                    {
                        string value = form.DataSources.UserDataSources.Item(alias).Value.Trim();
                        if (value.Length > 0)
                        {
                            if (uds[alias] == BoDataType.dt_DATE)//目前只处理时间
                            {
                                if (alias.EndsWith("_S"))
                                {
                                    conditions.Add(String.Format("{0} >= '{1}'", uds_field.Split(';').SingleOrDefault(s => s.Split(':')[0] == alias).Split(':')[1], form.DataSources.UserDataSources.Item(alias).Value.Trim()));
                                }
                                else if (alias.EndsWith("_E"))
                                {
                                    conditions.Add(String.Format("{0} <= '{1}'", uds_field.Split(';').SingleOrDefault(s => s.Split(':')[0] == alias).Split(':')[1], form.DataSources.UserDataSources.Item(alias).Value.Trim()));
                                }
                            }
                        }
                    }
                }
            }
            if (conditions.Count == 0)
            {
                app.MessageBox("还没有输入任何查询条件！");
                return 0;
            }
            Grid grid = form.Items.Item("grid").Specific;
            DataTable result = form.DataSources.DataTables.Item("DT_Result");
            //select = select + "From [" + tablename + "] WHERE " + String.Join(" AND ", conditions.ToArray());
            select = select ?? String.Format("select * from [{0}]", tablename);
            select += " WHERE " + String.Join(" AND ", conditions.ToArray());
            result.ExecuteQuery(select);
            grid.DataTable = result;
            grid.Columns.Item(0).Visible = false;
            for (int i = 0; i < grid.Columns.Count; i++)
            {
                grid.Columns.Item(i).Editable = false;
                Recordset rs = company.GetBusinessObject(BoObjectTypes.BoRecordset);
                string combo_table = String.Empty;
                switch (grid.Columns.Item(i).TitleObject.Caption)
                {
                    case "U_TransportType":
                    case "U_TransportMode":
                        combo_table = "[@AVA_FF_OMOT]";
                        break;
                    case "U_TrandeMethod":
                        combo_table = "[@AVA_FF_OTRM]";
                        break;
                    case "U_Bargain":
                        combo_table = "[@AVA_FF_BAMD]";
                        break;
                    case "UserSign":
                        combo_table = "[OUSR]";
                        break;
                    default:
                        combo_table = String.Empty;
                        break;
                }
                if (!String.IsNullOrEmpty(combo_table))
                {
                    if (combo_table == "[OUSR]")
                    {
                        //the ComboBoxColumn only accepts string values Message 
                        grid.Columns.Item(i).Type = SAPbouiCOM.BoGridColumnType.gct_ComboBox;
                        SAPbouiCOM.ComboBoxColumn cb = grid.Columns.Item(i) as SAPbouiCOM.ComboBoxColumn;
                        cb.DisplayType = SAPbouiCOM.BoComboDisplayType.cdt_Description;
                        rs.DoQuery("select USERID,U_NAME,USER_CODE from OUSR Where Locked = 'N'");
                        for (int j = 0; j < rs.RecordCount; j++)
                        {
                            cb.ValidValues.Add(rs.Fields.Item("USERID").Value, rs.Fields.Item("U_Name").Value);
                            rs.MoveNext();
                        }
                    }
                    else
                    {
                        grid.Columns.Item(i).Type = SAPbouiCOM.BoGridColumnType.gct_ComboBox;
                        SAPbouiCOM.ComboBoxColumn cb = grid.Columns.Item(i) as SAPbouiCOM.ComboBoxColumn;
                        cb.DisplayType = SAPbouiCOM.BoComboDisplayType.cdt_Description;
                        rs.DoQuery("select Code,Name from " + combo_table);
                        for (int j = 0; j < rs.RecordCount; j++)
                        {
                            cb.ValidValues.Add(rs.Fields.Item("Code").Value, rs.Fields.Item("Name").Value);
                            rs.MoveNext();
                        }
                    }
                }
                if (fields.ContainsKey(grid.Columns.Item(i).TitleObject.Caption))
                {
                    grid.Columns.Item(i).TitleObject.Caption = fields[grid.Columns.Item(i).TitleObject.Caption];
                    grid.Columns.Item(i).Visible = true;
                }
                else if (new Regex("[\u4e00-\u9fa5]+").Match(grid.Columns.Item(i).TitleObject.Caption).Success)
                {
                    grid.Columns.Item(i).Visible = true;//如果能匹配中文，则用中文别名
                }
                else
                {
                    grid.Columns.Item(i).Visible = false;
                }
            }
            if (result.Rows.Count == 1 && result.GetValue("DocEntry", 0) == 0)
            {
                app.MessageBox("没有查询到符合条件的结果，请重新设定条件进行查询");
                return 0;
            }
            else
            {
                app.StatusBar.SetText(String.Format("检索到{0}条结果", result.Rows.Count), BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Success);
                grid.AutoResizeColumns();
                return result.Rows.Count;
            }
        }
        #endregion
        #region 当前用户、部门、客服
        /// <summary>
        /// 获取当前用户
        /// </summary>
        /// <Author>WangPeng</Author>
        public static dynamic GetCurrentUser()
        {
            SAPbobsCOM.Recordset oRst;
            oRst = SAPBoAddon.B1Addon.B1Addon.SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
            string CurrentUser = string.Empty;
            string empID = string.Empty;
            string SQL_GetUser = @"SELECT T0.empID, T0.firstName+T0.lastName AS Name,T0.jobTitle  
                                   FROM [OHEM] T0 INNER JOIN [OUSR] T1 ON ISNULL(T0.userId,0)=T1.USERID 
                                   WHERE T1.USERID={0} ";
            oRst.DoQuery(string.Format(SQL_GetUser, SAPBoAddon.B1Addon.B1Addon.SBOCompany.UserSignature));
            if (oRst.RecordCount > 0)
            {
                empID = oRst.Fields.Item("empID").Value.ToString().Trim();
                if (!string.IsNullOrEmpty(oRst.Fields.Item("jobTitle").Value))
                {
                    CurrentUser = oRst.Fields.Item("jobTitle").Value.Trim();
                }
                else
                {
                    CurrentUser = oRst.Fields.Item("Name").Value;
                }
            }
            empID = string.IsNullOrEmpty(empID) ? "-1" : empID;
            return new { empID = empID, Operator = CurrentUser };
        }
        //指定部门及客服
        public static void SelectShowEmpId(SAPbouiCOM.DBDataSource dbds, string empName, bool service = true)
        {
            Recordset rs = SAPBoAddon.B1Addon.B1Addon.SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
            string empNameSelect = "SELECT empID FROM OHEM WHERE  jobTitle=N'{0}' Or (firstName+lastName) = '{0}'";
            empNameSelect = string.Format(empNameSelect, empName);
            rs.DoQuery(empNameSelect);
            if (rs.RecordCount > 0)
            {
                string empid = rs.Fields.Item("empID").Value.ToString().Trim();
                if (!string.IsNullOrEmpty(empid))
                {
                    int empId = Convert.ToInt32(empid);

                    //得到组别名称显示在窗体上
                    dbds.SetValue("U_Groups", dbds.Offset, GetDemptment(empId));
                    ////得到客服名称  /*带出的客服不正确 取消自动带出客服  modified by WangPeng 2012-4-20*/
                    if (service)
                    {
                        dbds.SetValue("U_ServiceName", dbds.Offset, GetClientService(empId));
                    }
                }
            }
        }

        /// <summary>
        /// 用户部门ID
        /// </summary>
        public static int GetDemptmentCode()
        {
            SAPbobsCOM.Recordset oRs;
            oRs = SAPBoAddon.B1Addon.B1Addon.SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
            string SQL = @"SELECT Department FROM [OUSR] WHERE USERID = {0}";
            SQL = string.Format(SQL, SAPBoAddon.B1Addon.B1Addon.SBOCompany.UserSignature);
            oRs.DoQuery(SQL);
            if (oRs.RecordCount > 0)
            {
                return oRs.Fields.Item("Department").Value;
            }
            return -1;
        }

        /// <summary>
        ///  得到团队管理者信息 得到 领导者名称
        /// </summary>
        public static string GetDemptment(int empID)
        {
            SAPbobsCOM.Recordset oRs;
            oRs = SAPBoAddon.B1Addon.B1Addon.SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
            string SQL = @"SELECT T1.Name
                                                FROM OHEM T0
	                                                INNER JOIN OUDP T1 ON T0.dept = T1.Code 
                                                Where T0.empID = {0}";
            string TeamLeaderName = string.Format(SQL, empID);
            oRs.DoQuery(TeamLeaderName);
            if (oRs.RecordCount > 0)
            {
                return oRs.Fields.Item("Name").Value;
            }
            return "";
        }
        /// <summary>
        ///  得到客服的角色名称
        /// </summary>
        public static string GetClientService(int empID)
        {
            SAPbobsCOM.Recordset ors;
            ors = SAPBoAddon.B1Addon.B1Addon.SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
            string SQL = @"
                                    SELECT T0.firstName+T0.lastName Name,T0.jobTitle
                                    FROM OHEM T0
	                                    INNER JOIN OHEM T1 ON T0.position = (SELECT TOP 1 posID FROM OHPS WHERE name='客服') And T0.dept = T1.dept
                                    Where T1.empID = {0}
                                    Order by T0.jobTitle";//按英文名称排序
            SQL = string.Format(SQL, empID);
            ors.DoQuery(SQL);
            if (ors.RecordCount > 0)
            {
                if (!string.IsNullOrEmpty(ors.Fields.Item("jobTitle").Value))
                    return ors.Fields.Item("jobTitle").Value;
                else
                    return ors.Fields.Item("Name").Value;
            }
            return "";
        }
        /// <summary>
        /// 重载的方法，显示全部客服
        /// </summary>
        /// <param name="cfl"></param>
        /// <author>Webb.Wen</author>
        /// <create>2012-03-10 10:33:18</create>
        public static void SelectClientName(SAPbouiCOM.ChooseFromList cfl)
        {
            SAPbouiCOM.Conditions cons = new SAPbouiCOM.Conditions();
            SAPbouiCOM.Condition con;
            Recordset rs = SAPBoAddon.B1Addon.B1Addon.SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
            rs.DoQuery(String.Format("select posID from OHPS where name = '客服'"));
            if (rs.RecordCount > 0)
            {
                con = cons.Add();
                con.Alias = "Position";
                con.CondVal = rs.Fields.Item("posID").Value.ToString().Trim();
                con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                cfl.SetConditions(cons);
            }
        }
        /// <summary>
        /// 根据组别选择相应客服
        /// </summary>
        public static void SelectClientName(SAPbouiCOM.ChooseFromList cfl, SAPbouiCOM.DBDataSource dbds)
        {
            SAPbouiCOM.Conditions cons = new SAPbouiCOM.Conditions();
            SAPbouiCOM.Condition con;
            string code = string.Empty;
            string ClientPosID = string.Empty;
            //获得组别名称 
            string groupName = dbds.GetValue("U_Groups", dbds.Offset).Trim();
            //查到组别ID
            SAPbobsCOM.Recordset oRs;
            oRs = SAPBoAddon.B1Addon.B1Addon.SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
            string groupIDStr = "SELECT TOP 1 Code FROM OUDP  WHERE Name='{0}'";
            groupIDStr = string.Format(groupIDStr, groupName);
            oRs.DoQuery(groupIDStr);
            if (oRs.RecordCount > 0)
                code = oRs.Fields.Item("Code").Value.ToString().Trim();
            //根据“客户”职位 查找客户表中的客户ID
            string getTeamClientInformation = @"SELECT TOP 1  posID FROM OHPS WHERE name='客服'";
            //查询客服posID使用
            SAPbobsCOM.Recordset oRsClient;
            oRsClient = SAPBoAddon.B1Addon.B1Addon.SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
            oRsClient.DoQuery(getTeamClientInformation);
            if (oRsClient.RecordCount > 0)
                ClientPosID = oRsClient.Fields.Item("posID").Value.ToString().Trim();
            //在OHEM表中查找 条件 dept==组别ID AND  Position==客户ID
            if ((!string.IsNullOrEmpty(code)) && (!string.IsNullOrEmpty(ClientPosID)))
            {
                con = cons.Add();
                con.Alias = "Position";
                con.CondVal = ClientPosID;
                con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                con.Relationship = SAPbouiCOM.BoConditionRelationship.cr_AND;
                con = cons.Add();
                con.Alias = "dept";
                con.CondVal = code;
                con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                cfl.SetConditions(cons);
            }
        }
        #endregion
        #region 基于Linq+Lambda的货物相关总计计算
        /// <summary>
        /// 半角转全角，老子怒了！
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string ToDBC(string input)
        {
            char[] c = input.ToCharArray();
            for (int i = 0; i < c.Length; i++)
            {
                if (c[i] == 12288)
                {
                    c[i] = (char)32;
                    continue;
                }
                if (c[i] > 65280 && c[i] < 65375)
                    c[i] = (char)(c[i] - 65248);
            }
            return new String(c);
        }
        /// <summary>
        /// 转成标准的日期格式
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static DateTime ToDatetime(string value)
        {
            if (value.Length < 8)
                throw (new Exception("不是合法的日期字符串"));
            string year = value.Substring(0, 4);
            string month = value.Substring(4, 2);
            string day = value.Substring(6, 2);
            return Convert.ToDateTime(year + "-" + month + "-" + day);
        }
        /// <summary>
        /// 基于Linq+Lambda的计算
        /// </summary>
        /// <param name="dbds"></param>
        /// <author>Webb.Wen</author>
        public static void CalculateVolumeAndQuantity(SAPbouiCOM.Application SBOApp, SAPbobsCOM.Company company, SAPbouiCOM.Form oForm, String DataTable, int Offset)
        {
            DBDataSource dbds = default(DBDataSource);
            try
            {
                if (oForm.Mode == BoFormMode.fm_FIND_MODE) return;

                dbds = oForm.DataSources.DBDataSources.Item(DataTable);

                double volume_rate = 0.0d;
                double size_rate = 0.0d;
                double volume_size_rate = 1.0d;
                string volume_unit = dbds.GetValue("U_VolumeUnit", Offset).Trim();
                string size_unit = dbds.GetValue("U_SizeUnit", Offset).Trim();

                Recordset rs = company.GetBusinessObject(BoObjectTypes.BoRecordset);
                rs.DoQuery(String.Format("select U_Rate from [@AVA_FF_OPRI] where Code = '{0}'", volume_unit));
                if (rs.RecordCount == 1)
                {
                    double.TryParse(rs.Fields.Item("U_Rate").Value.ToString(), out volume_rate);
                }
                rs.DoQuery(String.Format("select U_Rate from [@AVA_FF_OPRI] where Code = '{0}'", size_unit));
                if (rs.RecordCount == 1)
                {
                    double.TryParse(rs.Fields.Item("U_Rate").Value.ToString(), out size_rate);
                }

                if (volume_rate != 0.0d && size_rate != 0.0d)
                {
                    volume_size_rate = Math.Pow(volume_rate / size_rate, 3);//(CBM=1,CM=0.01,rate = 100)
                }

                //总体积计算（\r属于\s，所以只替换全半角空格）

                string cargo_size = ToDBC(Regex.Replace(dbds.GetValue("U_CargoSize", Offset).Trim(), @"[ 　]", ""));
                double volume = 0.0d;
                double quantity = 0.0d;
                if (cargo_size.Trim().Length > 0)
                {
                    if (GetFields(DataTable).ContainsKey("U_SingleWeightUnit"))//如果有单件重量则计算计费重
                    {
                        //计算总体积
                        string temp_volume = string.Empty;
                        string temp_weight = string.Empty;
                        IEnumerable<string> list = Regex.Split(cargo_size, "[\\s\r;]+").Where(item => (Regex.Split(item, @"[\*×xX]").Length == 5));
                        List<string> temp1 = new List<string>();
                        List<string> temp3 = new List<string>();
                        foreach (var item in list)
                        {
                            string[] temp2 = Regex.Split(item, @"[\*×xX]");
                            temp1.Add(String.Format("{0}*{1}*{2}*{3}", temp2[0], temp2[1], temp2[2], temp2[3]));
                            temp3.Add(String.Format("{0}*{1}", temp2[3], temp2[4]));
                        }
                        temp_volume = String.Join(";", temp1.ToArray());
                        temp_weight = String.Join(";", temp3.ToArray());
                        volume = Regex.Split(temp_volume, "[\\s\r;]+").Where(item => (Regex.Split(item, @"[\*×xX]").Length == 4)).Select(item => Regex.Split(item, @"[\*×xX]").Select(d => double.Parse(d)).Aggregate((i, j) => i * j)).Aggregate((i, j) => i + j);
                        dbds.SetValue("U_Volume", Offset, (volume / volume_size_rate).ToString());
                        //计算计费重
                        string gross_weight_unit = dbds.GetValue("U_GrossWeightUnit", Offset).Trim();
                        rs.DoQuery(String.Format("select U_Rate from [@AVA_FF_OPRI] where Code = '{0}'", gross_weight_unit));
                        double gross_weight_rate = 1.0d;
                        if (rs.RecordCount == 1)
                        {
                            double.TryParse(rs.Fields.Item("U_Rate").Value.ToString(), out gross_weight_rate);
                        }
                        string single_weight_unit = dbds.GetValue("U_SingleWeightUnit", Offset).Trim();
                        rs.DoQuery(String.Format("select U_Rate from [@AVA_FF_OPRI] where Code = '{0}'", single_weight_unit));
                        double single_weight_rate = 1.0d;
                        if (rs.RecordCount == 1)
                        {
                            double.TryParse(rs.Fields.Item("U_Rate").Value.ToString(), out single_weight_rate);
                        }
                        double billing_weight = Regex.Split(temp_weight, "[\\s\r;]+").Where(item => (Regex.Split(item, @"[\*×xX]").Length == 2)).Select(item => Regex.Split(item, @"[\*×xX]").Select(d => double.Parse(d)).Aggregate((i, j) => i * j)).Aggregate((i, j) => i + j);
                        dbds.SetValue("U_GrossWeight", Offset, (billing_weight * single_weight_rate / gross_weight_rate).ToString());
                    }
                    else
                    {
                        volume = Regex.Split(cargo_size, "[\\s\r;]+").Where(item => (Regex.Split(item, @"[\*×xX]").Length == 4)).Select(item => Regex.Split(item, @"[\*×xX]").Select(d => double.Parse(d)).Aggregate((i, j) => i * j)).Aggregate((i, j) => i + j);
                        dbds.SetValue("U_Volume", Offset, (volume / volume_size_rate).ToString());
                    }
                    quantity = Regex.Split(cargo_size, "[\\s\r;]+").Where(item => (Regex.Split(item, @"[\*×xX]").Length == 4 || Regex.Split(item, @"[\*×xX]").Length == 5)).Select(item => double.Parse(Regex.Split(item, @"[\*×xX]")[3])).Aggregate((i, j) => i + j);
                    dbds.SetValue("U_Quantity", dbds.Offset, quantity.ToString());
                }
            }
            catch (Exception ex)
            {
                //dbds.SetValue("U_CargoSize", Offset, "");
                SBOApp.MessageBox(String.Format("计算失败，原因：{0}", ex.Message));
            }
        }
        #endregion
        #region 获取当前用户
        /// <summary>
        /// 获取当前用户
        /// </summary>
        /// <param name="form"></param>
        /// <param name="company"></param>
        /// <returns></returns>
        public static void LoadUser(Form form, SAPbobsCOM.Company company, string ItmeUID)
        {
            ComboBox cb = form.Items.Item(ItmeUID).Specific as ComboBox;
            if (cb.ValidValues.Count > 0) return;
            Recordset rs = company.GetBusinessObject(BoObjectTypes.BoRecordset);
            string sql = String.Format("select USERID,U_NAME,USER_CODE from OUSR Where Locked = 'N'");
            rs.DoQuery(sql);
            for (int i = 0; i < rs.RecordCount; i++)
            {
                string UserID = rs.Fields.Item("USERID").Value.ToString();
                string Name = rs.Fields.Item("U_NAME").Value;
                if (string.IsNullOrEmpty(Name))
                    Name = rs.Fields.Item("USER_CODE").Value;
                cb.ValidValues.Add(UserID, Name);
                rs.MoveNext();
            }
        }
        #endregion
        #region Grid重排序
        /// <summary>
        /// 为Grid的列标头响应事件，单击时重新排序
        /// </summary>
        /// <param name="mtx"></param>
        /// <param name="ColumnUID"></param>
        public static void ReSort(Grid grid, string ColumnUID)
        {
            GridColumn column = grid.Columns.Item(ColumnUID);
            if (grid.Columns.Item(ColumnUID).TitleObject.Sortable)
            {
                grid.Columns.Item(ColumnUID).TitleObject.Sortable = true;
                column.TitleObject.Sort(SAPbouiCOM.BoGridSortType.gst_Ascending);
                grid.Columns.Item(ColumnUID).TitleObject.Sortable = false;
            }
            else
            {
                grid.Columns.Item(ColumnUID).TitleObject.Sortable = true;
                column.TitleObject.Sort(SAPbouiCOM.BoGridSortType.gst_Descending);
            }
        }
        #endregion
        #region 主分单联系人详细信息的处理
        public static void SelectAddressDetail(Form form, string ItemUID, string dbds, string field, string cardcode, bool Default = false)
        {
            string sql = string.Empty;
            if (Default == false)
            {
                sql = String.Format("select t0.[Address] ,t0.U_Address  from CRD1 t0 inner join OCRD t1 on t0.CardCode = t1.CardCode where AdresType = N'S' and t0.CardCode = N'{0}' ", cardcode);
            }
            else
            {
                sql = string.Format(@"select t0.[Address] ,t0.U_Address from CRD1 t0 inner join OCRD t1 on t0.CardCode = t1.CardCode 
                                where T0.AdresType = N'S' And T0.Address = T1.ShipToDef and t0.CardCode = N'{0}' ", cardcode);
                SAPbobsCOM.Recordset ors = SAPBoAddon.B1Addon.B1Addon.SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
                ors.DoQuery(sql);
                if (ors.RecordCount > 0)
                {
                    string detail = ors.Fields.Item("U_Address").Value.ToString().ToUpper();
                    SAPBoAddon.B1Assistant.DBDataSource.SBOApp.Forms.Item(form.UniqueID).DataSources.DBDataSources.Item(dbds).SetValue(field, 0, detail);
                }
                else
                {
                    SAPBoAddon.B1Assistant.DBDataSource.SBOApp.Forms.Item(form.UniqueID).DataSources.DBDataSources.Item(dbds).SetValue(field, 0, "");
                }
                System.Runtime.InteropServices.Marshal.FinalReleaseComObject(ors);
                return;
            }
            #region 地址列表实例化及配置
            SAPBoAddon.B1FormList.B1FormListSetting oFormListSetting = new SAPBoAddon.B1FormList.B1FormListSetting("AddressList", SAPBoAddon.B1FormList.FL_FillValueType.B1Edit);
            oFormListSetting.FormTitle = "地址-选择";
            oFormListSetting.FormType = form.TypeEx;
            oFormListSetting.FormUID = form.UniqueID;
            oFormListSetting.ListSQL = sql;
            oFormListSetting.dbDatasource = dbds;
            oFormListSetting.SelectionMode = BoMatrixSelect.ms_Single;
            oFormListSetting.ItemUID = ItemUID;
            oFormListSetting.MtxColumns.Title = "地址标识";
            oFormListSetting.MtxColumns.Add();
            oFormListSetting.MtxColumns.Title = "地址描述";
            oFormListSetting.MtxColumns.Add();
            oFormListSetting.FillSelectedField = field;

            SAPBoAddon.B1Addon.B1Addon.B1FormList.Form_CreateListForm(oFormListSetting);
            SAPBoAddon.B1Addon.B1Addon.B1FormList.B1ListFormEvent += new SAPBoAddon.B1FormList.B1FormList.B1ListFormEventEventHandler(B1FormList_B1ListFormEvent);
            #endregion
            if (form.Mode == BoFormMode.fm_OK_MODE)//防止点击后窗体状态不变 added by WangPeng [2012-7-25]
            {
                form.Mode = BoFormMode.fm_UPDATE_MODE;
            }
        }

        static void B1FormList_B1ListFormEvent(SAPBoAddon.B1FormList.B1FormListEvents pVal, ref bool BubbleEvent)
        {
            if (pVal.BeforeEvent == false)
            {
                pVal.CloseForm = false;
                string detail = pVal.SelectedDataTable.GetValue("U_Address", 0).ToString().ToUpper();
                SAPBoAddon.B1Assistant.DBDataSource.SBOApp.Forms.Item(pVal.FormUID).DataSources.DBDataSources.Item(pVal.dbDataSource).SetValue(pVal.FillSelectedField, 0, detail);
            }
        }
        #endregion
        #region 发送消息
        public static void SendMessage(SAPbobsCOM.Company company, string Subject, string MessageText, string UserCode, string DocEntry, string SerialNum, string ObjName)
        {
            int errCode;
            string errMsg;
            SAPbobsCOM.Messages oMsgs;
            oMsgs = company.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oMessages);

            oMsgs.Subject = Subject.Length > 50 ? Subject.Substring(0, 50) : Subject;
            oMsgs.MessageText = MessageText;
            oMsgs.Priority = SAPbobsCOM.BoMsgPriorities.pr_High;//优先级别           

            #region 收件人配置
            oMsgs.Recipients.Add();
            oMsgs.Recipients.UserCode = UserCode;
            oMsgs.Recipients.SendInternal = SAPbobsCOM.BoYesNoEnum.tYES;
            #endregion
            #region 信息内容
            oMsgs.AddDataColumn("单据编码", DocEntry, SAPbobsCOM.BoObjectTypes.oMessages, DocEntry);
            oMsgs.AddDataColumn("流水号", SerialNum, SAPbobsCOM.BoObjectTypes.oMessages, DocEntry);
            oMsgs.AddDataColumn("单据类型", ObjName, SAPbobsCOM.BoObjectTypes.oMessages, DocEntry);
            #endregion
            if (oMsgs.Add() != 0)
            {
                company.GetLastError(out errCode, out errMsg);
                throw (new Exception("发送系统信息错误：" + errMsg));
            }
        }
        #endregion
        #region 工具方法
        /// <summary>
        /// 将字段转化为描述
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="aliasIDs"></param>
        /// <returns></returns>
        public static List<string> AlaisID2Descr(string tableName, IEnumerable<string> aliasIDs)
        {
            Dictionary<string, string> fields = GetFields(tableName);
            List<string> result = new List<string>();
            IEnumerator enumerator = aliasIDs.GetEnumerator();
            while (enumerator.MoveNext())
            {
                if (fields.ContainsKey(enumerator.Current.ToString().Trim()))
                {
                    result.Add(fields[enumerator.Current.ToString().Trim()]);
                }
                else
                {
                    result.Add(enumerator.Current.ToString().Trim());
                }
            }
            return result;
        }
        /// <summary>
        /// 获取窗体中的控件
        /// </summary>
        /// <param name="FormXML"></param>
        /// <param name="ExceptionItemType">不包括的类型</param>
        /// <param name="ExceptionItemUID">不包括的Item</param>
        /// <returns></returns>
        public static string[] GetFormItems(XmlDocument oFormXml, bool Enable = true, string[] ExceptionItemUID = null, string[] ExceptionItemType = null)
        {
            string[] ItemType = default(string[]);
            if (ExceptionItemType == null)
            {
                ItemType = new string[] { "8", "99", "116" };
            }
            else
            {
                ItemType.CopyTo(ExceptionItemType, 0);
            }
            string XPath = "//item[@uid!='1' and @uid!='2']";
            string temp = string.Empty;
            foreach (string str in ItemType)
            {
                temp += "[@type!='" + str + "']";
            }
            XPath += temp;
            if (Enable)
                XPath += "[@enabled='1']";
            else
            {
                XPath += "[@enabled='0']";
            }
            System.Xml.XmlNodeList oNodeList = oFormXml.SelectNodes(XPath);
            ArrayList ItemsArrayList = new ArrayList();

            foreach (System.Xml.XmlNode oNode in oNodeList)
            {
                if (ExceptionItemUID != null)
                {
                    if (!ExceptionItemUID.Contains(oNode.Attributes["uid"].Value))
                    {
                        ItemsArrayList.Add(oNode.Attributes["uid"].Value);
                    }
                }
                else
                {
                    ItemsArrayList.Add(oNode.Attributes["uid"].Value);
                }
            }

            string[] Items = new string[ItemsArrayList.Count];
            for (int i = 0; i < ItemsArrayList.Count; i++)
            {
                Items[i] = ItemsArrayList[i].ToString();
            }
            return Items;
        }
        /// <summary>
        /// 解析窗体xml，将绑定字段映射成控件uid
        /// </summary>
        /// <param name="fields">要验证的字段</param>
        /// <returns>uid-field</returns>
        internal static Dictionary<string, string> GetFieldUIDMapping(Form form, string[] fields)
        {
            Dictionary<string, string> mapping = new Dictionary<string, string>();
            if (fields == null || fields.Length == 0)
                return mapping;
            XmlDocument xml = new XmlDocument();
            xml.LoadXml(form.GetAsXML());
            foreach (var item in fields)
            {
                if (!String.IsNullOrEmpty(item))
                {
                    XmlNode node = xml.ChildNodes[1].SelectSingleNode(String.Format("//item/specific/databind[@alias='{0}']", item));
                    if (node != null)
                    {
                        /*ChildNodes[1]是因为我懒了，不写也可以，
                         * "//child::node()//item/specific/databind[@alias='DocEntry']"也可以
                         * "//child::node()[1]//item/specific/databind[@alias='DocEntry']"也可以，反正针对srf文件是一个意思*/
                        string uid = node.ParentNode.ParentNode.Attributes["uid"].Value;
                        mapping.Add(uid, item);
                    }
                }
            }
            return mapping;
        }
        /// <summary>
        /// 解析窗体xml，将指定matrix绑定字段映射成列的uid
        /// </summary>
        /// <param name="mtx_uid">matrix的uid</param>
        /// <param name="fields">要验证的字段</param>
        /// <returns>uid-field</returns>
        internal static Dictionary<string, string> GetMatrixFieldUIDMapping(Form form, string mtx_uid, string[] fields)
        {
            Dictionary<string, string> mapping = new Dictionary<string, string>();
            if (fields == null || fields.Length == 0)
                return mapping;
            XmlDocument xml = new XmlDocument();
            xml.LoadXml(form.GetAsXML());
            foreach (var item in fields)
            {
                if (!String.IsNullOrEmpty(item))
                {
                    XmlNode node = xml.ChildNodes[1].SelectSingleNode(String.Format("//item[@uid='{0}']//column/databind[@alias='{1}']", mtx_uid, item));
                    string uid = node.ParentNode.Attributes["uid"].Value;
                    mapping.Add(uid, item);
                }
            }
            return mapping;
        }
        /// <summary>
        /// 分析DBDS的列
        /// </summary>
        /// <param name="dbds"></param>
        /// <param name="userDefinedOnly">是否仅分析用户自定义的列（U_开头）</param>
        /// <returns></returns>
        public static List<string> GetDbdsFields(DBDataSource dbds, bool userDefinedOnly = true)
        {
            List<string> fields = new List<string>();
            IEnumerator enumerator = dbds.Fields.GetEnumerator();
            while (enumerator.MoveNext())
            {
                SAPbouiCOM.Field field = enumerator.Current as SAPbouiCOM.Field;
                if (userDefinedOnly && !field.Name.StartsWith("U_")) { continue; }
                fields.Add(field.Name);
            }
            return fields;
        }
        /// <summary>
        /// 获取窗体的UserDataSource的UID-类型的集合
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        public static Dictionary<string, BoDataType> GetUserDataSource(Form form)
        {
            Dictionary<string, BoDataType> uds = new Dictionary<string, BoDataType>();
            IEnumerator enumerator = form.DataSources.UserDataSources.GetEnumerator();
            while (enumerator.MoveNext())
            {
                UserDataSource ud = enumerator.Current as UserDataSource;
                uds.Add(ud.UID, ud.DataType);
            }
            return uds;
        }
        /// <summary>
        /// 获取表的名称-描述的集合（通过DI）
        /// </summary>
        /// <param name="company"></param>
        /// <param name="tableName"></param>
        /// <returns></returns>
        public static Dictionary<string, string> GetFields(SAPbobsCOM.Company company, string tableName)
        {
            Dictionary<string, string> mapping = new Dictionary<string, string>();
            UserTable table = company.UserTables.Item(tableName);
            SAPbobsCOM.Fields fields = table.UserFields.Fields;
            for (int i = 0; i <= fields.Count - 1; i++)
            {
                SAPbobsCOM.Field field = fields.Item(i);
                mapping.Add(field.Name, field.Description);
            }
            return mapping;
        }
        /// <summary>
        /// 获取多个子表的Field
        /// </summary>
        /// <param name="company"></param>
        /// <param name="tableNames"></param>
        /// <returns></returns>
        public static Dictionary<string, string> GetFields(SAPbobsCOM.Company company, List<string> tableNames)
        {
            Dictionary<string, string> mapping = new Dictionary<string, string>();
            foreach (var item in tableNames)
            {
                Dictionary<string, string> t = GetFields(company, item);
                foreach (var m in t)
                {
                    if (!mapping.ContainsKey(m.Key))
                    {
                        mapping.Add(m.Key, m.Value);
                    }
                }
            }
            return mapping;
        }
        /// <summary>
        /// 从CUFD中查找自定义字段对应的描述值
        /// </summary>
        /// <param name="tableName"></param>
        /// <returns></returns>
        public static Dictionary<string, string> GetFields(string tableName)
        {
            Dictionary<string, string> fields = new Dictionary<string, string>();
            oRst.DoQuery(String.Format("SELECT AliasID,Descr FROM [CUFD] Where Sys = 'N' And TableID = '{0}'", tableName));
            if (oRst.RecordCount > 0)
            {
                for (int i = 0; i < oRst.RecordCount; i++)
                {
                    fields.Add("U_" + oRst.Fields.Item("AliasID").Value, oRst.Fields.Item("Descr").Value);
                    oRst.MoveNext();
                }
            }
            return fields;
        }
        public static Form GetForm(SAPbouiCOM.Application SBOApp, string FormUID)
        {
            IEnumerator enumerator = SBOApp.Forms.GetEnumerator();
            while (enumerator.MoveNext())
            {
                if ((enumerator.Current as Form).UniqueID == FormUID)
                {
                    return enumerator.Current as Form;
                }
            }
            return null;
        }
        public static void Dbds2DataTable(DBDataSource dbds, SAPbouiCOM.DataTable table, bool userDefinedOnly = true)
        {
            for (int i = 0; i < dbds.Fields.Count; i++)
            {
                SAPbouiCOM.Field field = dbds.Fields.Item(i);
                if (userDefinedOnly)
                {
                    if (field.Name.StartsWith("U_"))
                    {
                        table.Columns.Add(field.Name, field.Type, field.Size);
                    }
                }
                else
                {
                    table.Columns.Add(field.Name, field.Type, field.Size);
                }
            }
        }
        #endregion
        #region  打印/预览
        public static void SetPrintSetting(SAPbouiCOM.Application SBOApp, string TemplateFileName, string DocEntry)
        {
            TemplateFileName = TemplateFileName.Substring(0, TemplateFileName.Length - 4);
            string MenuUID = string.Empty;
            string SQL_GetMenuUID = string.Format("SELECT  MenuUID  FROM [OCMN] WHERE Name=N'{0}' AND Type='C' ", TemplateFileName);
            oRst.DoQuery(SQL_GetMenuUID);
            if (oRst.RecordCount > 0)
            {
                MenuUID = oRst.Fields.Item("MenuUID").Value;
            }
            else
            {
                SBOApp.StatusBar.SetText(string.Format("[{0}] 模板未导入系统.", TemplateFileName), BoMessageTime.bmt_Medium, BoStatusBarMessageType.smt_Error);
                return;
            }
            SBOApp.Menus.Item(MenuUID).Activate();

            SAPbouiCOM.Form oForm = SBOApp.Forms.ActiveForm;
            SAPbouiCOM.Item oItem = oForm.Items.Item("1000003");
            SAPbouiCOM.EditText oEdit = (SAPbouiCOM.EditText)oItem.Specific;
            oEdit.Value = DocEntry;
            oForm.Items.Item("1").Click();
        }
        #endregion
        #region 海运箱量总计描述/箱号总计描述/集装箱编码/计费重等自动计算
        /// <summary>
        /// 修改计费重时自动计算服务签中的计费重量
        /// </summary>
        /// <param name="cargo">货物DBDS</param>
        /// <param name="service">服务DBDS</param>
        /// <param name="standard">计费标准</param>
        /// <author>Webb.Wen</author>
        /// <create>2012-04-16 10:36:47</create>
        public static void CalcBillingWeight(DBDataSource cargo, DBDataSource service, string standard)
        {
            double grossWeight = 0.0d;
            double.TryParse(cargo.GetValue("U_GrossWeight", 0), out grossWeight);
            string grossWeightUnit = cargo.GetValue("U_GrossWeightUnit", 0).Trim();
            double volume = 0.0d;
            double.TryParse(cargo.GetValue("U_Volume", 0), out volume);
            string volumeUnit = cargo.GetValue("U_VolumeUnit", 0).Trim();
            double grossWeightUnitRate = 1.0d;
            double volumeUnitRate = 1.0d;
            oRst.DoQuery(String.Format("select U_Rate from [@AVA_FF_OPRI] where Code = '{0}'", grossWeightUnit));
            if (oRst.RecordCount > 0)
            {
                double.TryParse(oRst.Fields.Item("U_Rate").Value.ToString(), out grossWeightUnitRate);
            }
            oRst.DoQuery(String.Format("select U_Rate from [@AVA_FF_OPRI] where Code = '{0}'", volumeUnit));
            if (oRst.RecordCount > 0)
            {
                double.TryParse(oRst.Fields.Item("U_Rate").Value.ToString(), out volumeUnitRate);
            }
            grossWeight = grossWeight * grossWeightUnitRate / 1000;//重量的参考标准值是kg，这里要以t为单位，要转一次
            volume = volume * volumeUnitRate;
            service.SetValue("U_Weight", 0, grossWeight >= volume ? grossWeight.ToString() : volume.ToString());
            service.Offset = 0;
            switch (standard.ToUpper())
            {
                case "1000KGS":
                    break;
                case "CBM":
                    break;
                case "363KGS":
                    break;
                case "330KBS":
                    break;
                case "500KGS":
                    break;
                //蓝蓝 2012/3/28 17:05:50
                //计算规则一样的
            }
        }
        /// <summary>
        /// 修改服务签中的计费重量时自动修改货物的毛重
        /// </summary>
        /// <param name="cargo"></param>
        /// <author>Webb.Wen</author>
        /// <create>2012-04-16 10:36:47</create>
        public static void SetCargoGrossWeight(DBDataSource cargo, string value)
        {
            double grossWeight = 0.0d; ;
            double.TryParse(cargo.GetValue("U_GrossWeight", 0), out grossWeight);
            string grossWeightUnit = cargo.GetValue("U_GrossWeightUnit", 0).Trim();
            double grossWeightUnitRate = 1.0d;
            oRst.DoQuery(String.Format("select U_Rate from [@AVA_FF_OPRI] where Code = '{0}'", grossWeightUnit));
            if (oRst.RecordCount > 0)
            {
                double.TryParse(oRst.Fields.Item("U_Rate").Value.ToString(), out grossWeightUnitRate);
            }
            double.TryParse(value, out grossWeight);
            grossWeight = grossWeight * grossWeightUnitRate;
            cargo.SetValue("U_GrossWeight", 0, grossWeight.ToString());
        }
        /// <summary>
        /// 将阿拉伯数字转换成英文的委托，如果我的算法有问题可以替换成其它算法
        /// </summary>
        /// <param name="ArabicNumber"></param>
        /// <returns></returns>
        /// <author>Webb.Wen</author>
        /// <create>2012-04-16 10:36:47</create>
        public delegate string Translate(double ArabicNumber);
        /// <summary>
        /// 获取业务单的总箱量并自动转换成箱量总计描述
        /// 箱量总计描述= SAY （箱量总计英文）CONTAINER(S) ONLY（如果是FCL，从服务里取；如果是LCL，从装箱里取箱量总计）
        /// </summary>
        /// <param name="BNOFromUID"></param>
        /// <author>Webb.Wen</author>
        /// <create>2012-04-16 10:36:47</create>
        public static void SetBoxAndCargoQuantityDescription(SAPbouiCOM.Application SBOApp, string BNOFromUID, Translate translate, string containerType = null, string TableName = "@AVA_SE_OBNO")
        {
            Form BNOForm = SBOApp.Forms.Item(BNOFromUID);
            DBDataSource OBNO = BNOForm.DataSources.DBDataSources.Item(TableName);
            DBDataSource BNO1 = BNOForm.DataSources.DBDataSources.Item(OBNO.TableName.Remove(8, 1) + "1");
            DBDataSource BNO2 = BNOForm.DataSources.DBDataSources.Item(OBNO.TableName.Remove(8, 1) + "2");
            DBDataSource BNO3 = BNOForm.DataSources.DBDataSources.Item(OBNO.TableName.Remove(8, 1) + "3");
            DBDataSource BNO4 = BNOForm.DataSources.DBDataSources.Item(OBNO.TableName.Remove(8, 1) + "4");
            DBDataSource BNO5 = BNOForm.DataSources.DBDataSources.Item(OBNO.TableName.Remove(8, 1) + "5");
            DBDataSource BNO6 = BNOForm.DataSources.DBDataSources.Item(OBNO.TableName.Remove(8, 1) + "6");

            string boxDescription = String.Empty;
            string cargoDescription = String.Empty;
            double boxQuantity = 0;
            double cargoQuantity = 0;
            string boxQtyString = String.Empty;
            /*一个奇怪的现象，即使是事件后，点击LCL，获取DBDS里的U_ContainerType，得到的也是FCL对应的1*/
            string U_ContainerType = String.IsNullOrEmpty(containerType) ? OBNO.GetValue("U_ContainerType", 0).ToString().Trim() : containerType;

            //货物总计都从货物表里取
            for (int i = 0; i < OBNO.Size; i++)
            {
                double quantity = 0.0d;
                Double.TryParse(OBNO.GetValue("U_Quantity", i), out quantity);
                cargoQuantity += quantity;
            }
            #region LCL
            if (U_ContainerType == "2" || U_ContainerType == "LCL")
            {
                string PCKListFormUID = BNOForm.DataSources.UserDataSources.Item("OPCK_UID").Value.Trim();
                if (!String.IsNullOrWhiteSpace(PCKListFormUID))
                {
                    Form PCKListForm = SBOApp.Forms.Item(PCKListFormUID);
                    Grid grid = PCKListForm.Items.Item("Grid").Specific;

                    for (int i = 0; i < grid.DataTable.Rows.Count; i++)
                    {
                        string entry = grid.DataTable.GetValue("DocEntry", i).ToString().Trim();
                        string formUid = grid.DataTable.GetValue("FormUID", i).ToString().Trim();
                        if (!String.IsNullOrEmpty(formUid) && Utils.GetForm(SBOApp, formUid) != null)//说明窗体已经打开，并且可能已经被编辑，所以数据库数据不一定准确，此时从DBDS里去取
                        {
                            Form PCKForm = SBOApp.Forms.Item(formUid);
                            DBDataSource dbds1 = PCKForm.DataSources.DBDataSources.Item("@AVA_SE_PCK1");
                            for (int ii = 0; ii < dbds1.Size; ii++)
                            {
                                double q = 0;
                                double.TryParse(dbds1.GetValue("U_Quantity", ii), out q);
                                boxQuantity += q;
                            }
                            //DBDataSource dbds2 = PCKForm.DataSources.DBDataSources.Item("@AVA_SE_PCK2");
                            //for (int ii = 0; ii < dbds2.Size; ii++)
                            //{
                            //    double q = 0;
                            //    double.TryParse(dbds2.GetValue("U_Quantity", ii), out q);
                            //    cargoQuantity += q;
                            //}
                        }
                        else//如果FormUID为空，说明窗体只是加载到列表里而没有打开，这个时候去数据库取
                        {
                            string sql = String.Format("select SUM(U_Quantity) as [SumQuantity] from [@AVA_SE_PCK1] where DocEntry = {0}", entry);
                            oRst.DoQuery(sql);
                            if (oRst.RecordCount == 1)
                            {
                                double q = 0;
                                double.TryParse(oRst.Fields.Item("SumQuantity").Value, out q);
                                boxQuantity += q;
                            }
                            //sql = String.Format("select SUM(U_Quantity) as [SumQuantity] from [@AVA_SE_PCK2] where DocEntry = {0}", entry);
                            //if (oRst.RecordCount == 1)
                            //{
                            //    double q = 0;
                            //    double.TryParse(oRst.Fields.Item("SumQuantity").Value, out q);
                            //    cargoQuantity += q;
                            //}
                            //sql = String.Format("select SUM(U_Quantity) as [SumQuantity] from [@AVA_SE_BNO1] where DocEntry = {0}", BNOForm.DataSources.DBDataSources.Item("@AVA_SE_OBNO").GetValue("DocEntry", 0).Trim());
                            //if (oRst.RecordCount == 1)
                            //{
                            //    double q = 0;
                            //    double.TryParse(oRst.Fields.Item("SumQuantity").Value, out q);
                            //    cargoQuantity += q;
                            //}

                        }
                    }
                }
                boxQtyString = "LCL";
            }
            #endregion
            #region FCL
            else if (U_ContainerType == "1" || U_ContainerType == "FCL")//FCL
            {
                //DBDataSource dbds = BNOForm.DataSources.DBDataSources.Item("@AVA_SE_BNO6");
                Dictionary<string, int> QtyList = new Dictionary<string, int>();
                List<string> boxQtyList = new List<string>();
                for (int i = 0; i < BNO6.Size; i++)
                {
                    int Qty;
                    if (QtyList.TryGetValue(BNO6.GetValue("U_BoxType", i).Trim(), out Qty) == false)
                    {
                        QtyList.Add(BNO6.GetValue("U_BoxType", i).Trim(), 1);
                    }
                    else
                    {
                        Qty += 1;
                        QtyList[BNO6.GetValue("U_BoxType", i).Trim()] = Qty;
                    }
                }
                foreach (var item in QtyList)
                {
                    boxQtyList.Add(String.Format("{0}×{1}", item.Key, item.Value));
                }
                boxQtyString = String.Join(" ", boxQtyList);
            }
            #endregion
            #region BULK
            else if (U_ContainerType == "3" || U_ContainerType == "BULK")//BULK
            {
                boxQuantity = 0.0d;//散货没有箱量的概念
                boxQtyString = "";
            }
            #endregion
            boxDescription = boxQuantity > 0 ? String.Format("SAY {0} CONTAINER(S) ONLY", translate(boxQuantity)) : "";
            if (cargoQuantity > 0)
            {
                string unit = BNO1.GetValue("U_QuantityUnit", 0).ToString().Trim();
                oRst.DoQuery(String.Format("select Name from [@AVA_FF_OPRI] where Code = '{0}'", unit));
                if (oRst.RecordCount == 1)
                {
                    unit = oRst.Fields.Item("Name").Value;
                    unit = cargoQuantity == 1.0d ? unit : String.Format("{0}(S)", unit);
                    cargoDescription = String.Format("SAY {0}({1}) {2} ONLY", translate(cargoQuantity), (int)cargoQuantity, unit);
                }
            }
            else
            {
                cargoDescription = "";
            }
            //海运没有一级代理，所以基本不维护主单数据（2012-04-20 11:04:55 by Erika）
            //一级代理时就需要维护
            if (OBNO.GetValue("U_IsDBL", OBNO.Offset).Trim() == "Y")
            {
                BNO3.SetValue("U_BoxQty", 0, boxQtyString);
                BNO3.SetValue("U_BoxQtyTotalDesc", 0, boxDescription);
            }
            BNO3.SetValue("U_CargoQtyTotalDesc", 0, cargoDescription);
            BNO4.SetValue("U_BoxQty", 0, boxQtyString);
            BNO4.SetValue("U_BoxQtyTotalDesc", 0, boxDescription);
            BNO4.SetValue("U_CargoQtyTotalDesc", 0, cargoDescription);
        }
        /// <summary>
        /// 设置箱号和封条号
        /// </summary>
        /// <param name="SBOApp"></param>
        /// <param name="BNOFromUID"></param>
        /// <author>Webb.Wen</author>
        /// <date>2012-04-16 15:27:55</date>
        public static void SetBoxAndSealNumber(SAPbouiCOM.Application SBOApp, string BNOFromUID)
        {
            Form BNOForm = SBOApp.Forms.Item(BNOFromUID);
            List<string> numbers = new List<string>();
            string PCKListFormUID = BNOForm.DataSources.UserDataSources.Item("OPCK_UID").Value.Trim();
            if (!String.IsNullOrWhiteSpace(PCKListFormUID))
            {
                Form PCKListForm = SBOApp.Forms.Item(PCKListFormUID);
                Grid grid = PCKListForm.Items.Item("Grid").Specific;

                for (int i = 0; i < grid.DataTable.Rows.Count; i++)
                {
                    string entry = grid.DataTable.GetValue("DocEntry", i).ToString().Trim();
                    string formUid = grid.DataTable.GetValue("FormUID", i).ToString().Trim();
                    if (String.IsNullOrEmpty(formUid))//如果FormUID为空，说明窗体只是加载到列表里而没有打开，这个时候去数据库取
                    {
                        string sql = String.Format("select U_BoxNumber,U_SealNumber from [@AVA_SE_PCK1] where DocEntry = {0}", entry);
                        oRst.DoQuery(sql);
                        for (int ii = 0; ii < oRst.RecordCount; ii++)
                        {
                            numbers.Add(String.Format(@"{0}\{1}", oRst.Fields.Item("U_BoxNumber").Value.ToString().Trim(), oRst.Fields.Item("U_SealNumber").Value.ToString().Trim()));
                            oRst.MoveNext();
                        }
                    }
                    else//否则说明窗体已经打开，并且可能已经被编辑，所以数据库数据不一定准确，此时从DBDS里去取
                    {
                        Form PCKForm = SBOApp.Forms.Item(formUid);
                        DBDataSource dbds1 = PCKForm.DataSources.DBDataSources.Item("@AVA_SE_PCK1");
                        for (int ii = 0; ii < dbds1.Size; ii++)
                        {
                            if (!String.IsNullOrWhiteSpace(dbds1.GetValue("U_BoxNumber", ii).ToString().Trim()))
                            {
                                numbers.Add(String.Format(@"{0}\{1}", dbds1.GetValue("U_BoxNumber", ii).ToString().Trim(), dbds1.GetValue("U_SealNumber", ii).ToString().Trim()));
                            }
                        }
                    }
                }
            }
            BNOForm.DataSources.DBDataSources.Item("@AVA_SE_BNO3").SetValue("U_BoxCode", 0, String.Join("\r\n", numbers));
            BNOForm.DataSources.DBDataSources.Item("@AVA_SE_BNO4").SetValue("U_BoxCode", 0, String.Join("\r\n", numbers));
            if (BNOForm.Mode != BoFormMode.fm_ADD_MODE || BNOForm.Mode != BoFormMode.fm_UPDATE_MODE)
                BNOForm.Mode = BoFormMode.fm_UPDATE_MODE;
        }
        /// <summary>
        /// 集装箱编号最后一位验证码的计算公式
        /// 参考资料：http://club.excelhome.net/thread-676415-1-1.html
        /// </summary>
        /// <param name="OwnerCode">四位英文集装箱说明代码</param>
        /// <param name="RegistrationCode">六位数字箱体注册码</param>
        /// <returns>最后一位验证码</returns>
        /// <author>Webb.Wen</author>
        /// <date>2012-04-17 11:55:15</date>
        public static string GetCheckDigit(string OwnerCode, string RegistrationCode)
        {
            /*验证：
             *REGU319765 3
              CCLU695652 5
              OOLU850480 7
              TEXU000043 7
              MLCU255651 7
             */
            if (Regex.IsMatch(OwnerCode, @"^[\w]{4}$") && Regex.IsMatch(RegistrationCode, @"^[\d]{6}$"))
            {
                object result = (OwnerCode + RegistrationCode).ToCharArray().Select((x, i) => Convert.ToInt32(new Regex(String.Format(@"(?<={0}=)\d+(?=/)", x.ToString().ToUpper())).Match("0=0/1=1/2=2/3=3/4=4/5=5/6=6/7=7/8=8/9=9/A=10/B=12/C=13/D=14/E=15/F=16/G=17/H=18/I=19/J=20/K=21/L=23/M=24/N=25/O=26/P=27/Q=28/R=29/S=30/T=31/U=32/V=34/W=35/X=36/Y=37/Z=38").Value) * Math.Pow(2, (i + 1 - 1))).Aggregate((i, j) => i + j) % 11;

                return (Convert.ToInt32(result) == 10 ? 0 : result).ToString();//如果是10，则处理成0，11取模10是合法结果
            }
            return "";
        }
        #endregion
        #region 业务单窗体的子单据操作
        internal static string GetNextEntry(string objectType)
        {
            //更新最新的DocEntry
            string onnm = String.Format("select AutoKey,DfltSeries from ONNM WITH(UPDLOCK) where ObjectCode = '{0}'", objectType);
            oRst.DoQuery(onnm);
            string AutoKey = oRst.Fields.Item("AutoKey").Value.ToString();
            return AutoKey;
        }
        /// <summary>
        /// 显示一个子单据窗体
        /// </summary>
        /// <param name="SBOApp"></param>
        /// <param name="listFormUID"></param>
        /// <param name="index">列表窗体中的行号</param>
        /// <param name="showForm"></param>
        internal static void ShowSonForm(SAPbouiCOM.Application SBOApp, string listFormUID, int index, ShowFormDelegate showForm)
        {
            Form listForm = GetForm(SBOApp, listFormUID);
            if (listForm != null)
            {
                Grid grid = listForm.Items.Item("Grid").Specific as Grid;
                if (index + 1 <= grid.Rows.Count)
                {
                    string sonEntry = grid.DataTable.GetValue("DocEntry", index).ToString().Trim();
                    string sonFormUID = grid.DataTable.GetValue("FormUID", index).ToString().Trim();
                    Form sonForm = GetForm(SBOApp, sonFormUID);
                    if (sonForm != null)
                    {
                        sonForm.Visible = true;
                    }
                    else
                    {
                        string sonType = listForm.DataSources.UserDataSources.Item("SonType").Value.Trim();
                        string BNOEntry = listForm.DataSources.UserDataSources.Item("BNOEntry").Value.Trim();
                        string parms = String.Format("{0};{1};{2}", listFormUID, BNOEntry, sonEntry);

                        showForm(sonType, parms);
                    }
                }
            }
            else
            {
                SBOApp.SetStatusBarMessage("列表窗体已经关闭，请双击重新打开", BoMessageTime.bmt_Short, false);
            }
        }
        /// <summary>
        /// 新增一个子单据窗体
        /// </summary>
        /// <param name="SBOApp"></param>
        /// <param name="listFormUID"></param>
        /// <param name="showForm"></param>
        internal static void AddSonForm(SAPbouiCOM.Application SBOApp, string listFormUID, ShowFormDelegate showForm)
        {
            Form listForm = GetForm(SBOApp, listFormUID);
            if (listForm != null)
            {
                Grid grid = listForm.Items.Item("Grid").Specific as Grid;

                string sonType = listForm.DataSources.UserDataSources.Item("SonType").Value.Trim();
                string BNOEntry = listForm.DataSources.UserDataSources.Item("BNOEntry").Value.Trim();
                string sonTable = listForm.DataSources.UserDataSources.Item("SonTable").Value.Trim().Split('/')[0];

                string parms = String.Format("{0};{1};{2}", listForm.UniqueID, BNOEntry, "");

                showForm(sonType, parms);//子窗体需要回写grid，新增一行，赋值DocEntry列；给SonEntry_SonFormUID赋值
            }
            else
            {
                SBOApp.SetStatusBarMessage("列表窗体已经关闭，请双击重新打开", BoMessageTime.bmt_Short, false);
            }
        }
        /// <summary>
        /// 更新列表窗体的列表
        /// </summary>
        /// <param name="SBOApp"></param>
        /// <param name="listFormUID"></param>
        /// <param name="sonFormUID"></param>
        /// <param name="sonEntry"></param>
        internal static void UpdateListFormGrid(SAPbouiCOM.Application SBOApp, string listFormUID, string sonFormUID, string sonEntry)
        {
            Form listForm = GetForm(SBOApp, listFormUID);
            if (listForm != null)
            {
                Grid grid = listForm.Items.Item("Grid").Specific as Grid;
                for (int i = 0; i < grid.DataTable.Rows.Count; i++)
                {
                    if (grid.DataTable.GetValue("DocEntry", i).ToString() == sonEntry)
                    {
                        grid.DataTable.SetValue("FormUID", i, sonFormUID);
                        return;//如果存在，更新并退出函数
                    }
                }
                if (grid.DataTable.Rows.Count > 0 && grid.DataTable.GetValue("DocEntry", 0).ToString() == "0")//默认有一个空行，DocEntry=0
                {
                    grid.DataTable.Rows.Remove(0);
                }
                grid.DataTable.Rows.Add();//否则新增
                grid.DataTable.SetValue("DocEntry", grid.DataTable.Rows.Count - 1, sonEntry);
                grid.DataTable.SetValue("FormUID", grid.DataTable.Rows.Count - 1, sonFormUID);
            }
            else
            {
                SBOApp.SetStatusBarMessage("列表窗体已经关闭，请双击重新打开", BoMessageTime.bmt_Short, false);
            }
        }
        /// <summary>
        /// 删除一个子单据窗体
        /// </summary>
        /// <param name="SBOApp"></param>
        /// <param name="listFormUID"></param>
        internal static void DeleteSonForm(SAPbouiCOM.Application SBOApp, string listFormUID)
        {
            Form listForm = GetForm(SBOApp, listFormUID);
            if (listForm != null)
            {
                Grid grid = listForm.Items.Item("Grid").Specific as Grid;
                for (int gridrow = 0; gridrow < grid.Rows.Count; gridrow++)
                {
                    if (grid.Rows.IsSelected(gridrow))
                    {
                        int dialogResult = SBOApp.MessageBox("数据删除后不可恢复，确认删除该条数据？", 2, "确定", "取消");
                        if (dialogResult == 1)
                        {
                            string sonType = listForm.DataSources.UserDataSources.Item("SonType").Value.Trim();
                            string BNOEntry = listForm.DataSources.UserDataSources.Item("BNOEntry").Value.Trim();

                            string[] sonTables = listForm.DataSources.UserDataSources.Item("SonTable").Value.Trim().Split('/');

                            string sonEntry = grid.DataTable.GetValue("DocEntry", gridrow).ToString().Trim();

                            for (int i = sonTables.Length - 1; i >= 0; i--)
                            {
                                oRst.DoQuery(String.Format("update [{0}] set U_BaseEntry = null where DocEntry={1}", sonTables[i], sonEntry));
                            }
                            string sonFormUID = grid.DataTable.GetValue("FormUID", gridrow);
                            Form sonForm = GetForm(SBOApp, sonFormUID);
                            if (sonForm != null)
                            {
                                sonForm.Items.Item("2").Visible = true;
                                sonForm.Items.Item("2").Click(BoCellClickType.ct_Regular);//关闭子窗体
                            }

                            grid.DataTable.Rows.Remove(gridrow);//从列表移除
                            SBOApp.StatusBar.SetText(String.Format("删除成功！"), BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Success);
                        }
                    }
                }
            }
            else
            {
                SBOApp.SetStatusBarMessage("列表窗体已经关闭，请双击重新打开", BoMessageTime.bmt_Short, false);
            }
        }
        #endregion
        #region 通过为单据的备注赋值，以使得关闭窗体时有提示是否关闭信息
        /// <summary>
        /// 通过为单据的备注赋值，以使得关闭窗体时有提示是否关闭信息 
        /// </summary>
        /// <author>WangPeng</author>
        internal static void SetRemarkByItem(SAPbouiCOM.Form CurrentForm, string ItemUID_Remark = "13", string strRemarkVal = "此处不能赋空字符，别着急，随便赋值也没问题，后面会给覆盖掉的~")
        {
            (CurrentForm.Items.Item(ItemUID_Remark).Specific as SAPbouiCOM.EditText).Value = strRemarkVal;
        }
        #endregion
        #region 发货公司，接货公司 联系人
        /// <summary>
        /// 设置发货公司、接货公司地址过滤
        /// </summary>
        /// <author>WangPeng</author>
        public static void ChooseFromListAddress_Filter(SAPbouiCOM.Form CurrentForm, ref SAPbouiCOM.ChooseFromList cfl, string CurrentTableName, string FieldName_CardCode, SAPbouiCOM.Conditions cons, SAPbouiCOM.Condition con, ref bool BubbleEvent)
        {
            SAPbouiCOM.DBDataSource dbds = CurrentForm.DataSources.DBDataSources.Item(CurrentTableName);
            string CardCode = dbds.GetValue(FieldName_CardCode, dbds.Offset).ToString().Trim();
            if (string.IsNullOrEmpty(CardCode))
            {
                BubbleEvent = false;
                SAPBoAddon.B1Addon.B1Addon.SBOApp.StatusBar.SetText("请先选择 公司..", BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Error);

                return;
            }
            cons = new SAPbouiCOM.Conditions();
            con = cons.Add();
            con.Alias = "CardCode";
            con.CondVal = CardCode;
            con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
            con.Relationship = BoConditionRelationship.cr_AND;
            con = cons.Add();
            con.Alias = "U_IsWhsAddress";
            con.CondVal = "Y";
            con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
            cfl.SetConditions(cons);
        }

        /// <summary>
        /// 获取客户联系人地址
        /// </summary>
        /// <author>WangPeng</author>
        public static string GetAddress(SAPBoAddon.B1AddonBase.B1ChooseFormList pVal)
        {
            string str_SelectedAddress = string.Empty;
            for (int i = 0; i < pVal.SelectedObjects.Rows.Count; i++)
            {
                if (!string.IsNullOrEmpty(pVal.SelectedObjects.GetValue("Address", i).ToString()))
                {
                    str_SelectedAddress += string.Format("{0};", pVal.SelectedObjects.GetValue("Address", i).ToString());
                }
            }
            return str_SelectedAddress;
        }
        #endregion
        #region
        /// <summary>
        /// 为其他窗体的包装类型赋值
        /// </summary>
        /// <author>WangPeng</author>
        public static void SetPackType(FormType_PackType Uds_OtherListFormUID, SAPbouiCOM.Form Form_OBNO)
        {
            string ItemUID_PackType = "109";

            string ListFormUID = Form_OBNO.DataSources.UserDataSources.Item(Uds_OtherListFormUID.ToString()).ValueEx;
            if (string.IsNullOrEmpty(ListFormUID))
            {
                return;
            }
            SAPbouiCOM.Form List_Form = SAPBoAddon.B1Addon.B1Addon.SBOApp.Forms.Item(ListFormUID);
            SAPbouiCOM.Grid Grid_ChildForm = List_Form.Items.Item("Grid").Specific;
            SAPbouiCOM.Form Form_OtherPack;
            string FormUID_Child = string.Empty;
            string PackType = Form_OBNO.DataSources.UserDataSources.Item("PackType").ValueEx;
            SAPbouiCOM.EditText oItem_PackType;
            SAPbouiCOM.DBDataSource dbds_Other;
            string Alias_PackType = string.Empty;
            if (Uds_OtherListFormUID == FormType_PackType.OARP_UID)
            {
                ItemUID_PackType = "67";
            }


            for (int i = 0; i < Grid_ChildForm.Rows.Count; i++)
            {
                FormUID_Child = Grid_ChildForm.DataTable.GetValue(1, 0);/*子窗体的FormUID*/
                Form_OtherPack = SAPBoAddon.B1Addon.B1Addon.SBOApp.Forms.Item(FormUID_Child);

                oItem_PackType = Form_OtherPack.Items.Item(ItemUID_PackType).Specific as SAPbouiCOM.EditText;
                dbds_Other = Form_OtherPack.DataSources.DBDataSources.Item(oItem_PackType.DataBind.TableName);
                Alias_PackType = oItem_PackType.DataBind.Alias;
                dbds_Other.SetValue(Alias_PackType, dbds_Other.Offset, PackType);
            }

        }

        /// <summary>
        /// 计算行总计
        /// </summary>
        /// <author>WangPeng</author>
        internal static void CalcLineTotal(SAPbouiCOM.Form oForm, string MatrixUID, string dbds_Table, int Row)
        {
            SAPbouiCOM.Matrix oMtx = oForm.Items.Item(MatrixUID).Specific;
            SAPbouiCOM.DBDataSource dbds = oForm.DataSources.DBDataSources.Item(dbds_Table);
            SAPbouiCOM.DBDataSource dbds_Main = oForm.DataSources.DBDataSources.Item(dbds_Table.Remove(dbds_Table.Length - 1).Insert(dbds_Table.LastIndexOf("_") + 1, "O"));

            dbds.Offset = SAPBoAddon.B1Assistant.Matrix.GetdbDsOffset(oMtx, Row, "col_f", dbds);
            oMtx.GetLineData(Row);
            decimal LineTotal = 0;
            decimal Quantity = Convert.ToDecimal(dbds.GetValue("U_Quantity", dbds.Offset).Trim());
            decimal Price = Convert.ToDecimal(dbds.GetValue("U_Price", dbds.Offset).Trim());
            LineTotal = Quantity * Price;
            dbds.SetValue("U_Total", dbds.Offset, decimal.Round(LineTotal, 4).ToString());
            oMtx.SetLineData(Row);

            decimal DocTotal = 0;
            for (int i = 0; i < dbds.Size; i++)
            {
                DocTotal += Convert.ToDecimal(dbds.GetValue("U_Total", i).Trim());
            }
            dbds_Main.SetValue("U_TotalAmount", dbds_Main.Offset, decimal.Round(DocTotal, 3).ToString());
        }

        /// <summary>
        /// 取业务单的ATD日期
        /// </summary>
        /// <param name="BopEntry">业务单号</param>
        /// <author>WangPeng</author>
        internal static string GetBopATDDate(string BopEntry, string BPType)
        {
            #region 业务单类型-表 字典
            Dictionary<string, string> Dic_BoTypeDS = new Dictionary<string, string>();
            Dic_BoTypeDS.Add("A", "@AVA_FF_OBNO");
            Dic_BoTypeDS.Add("S", "@AVA_SE_OBNO");
            Dic_BoTypeDS.Add("L", "@AVA_LN_OBNO");
            Dic_BoTypeDS.Add("O", "@AVA_OR_OBNO");
            #endregion
            //= this.CurrentForm.DataSources.UserDataSources.Item("BoType").ValueEx.Trim();
            if (string.IsNullOrEmpty(BopEntry) || string.IsNullOrEmpty(BPType)) return DateTime.Now.ToShortDateString();
            string TableName = Dic_BoTypeDS[BPType];
            DateTime Date_ATD;
            string SQL_GetBoATD = string.Format("SELECT ISNULL(U_ATD,GETDATE()) as U_ATD  FROM [{0}] WHERE DocEntry={1} ", TableName, BopEntry);
            oRst.DoQuery(SQL_GetBoATD);
            if (oRst.RecordCount > 0)
            {
                Date_ATD = oRst.Fields.Item("U_ATD").Value;
            }
            else
            {
                SAPBoAddon.B1Addon.B1Addon.SBOApp.StatusBar.SetText("业务单未维护ATD日期", BoMessageTime.bmt_Medium, BoStatusBarMessageType.smt_Warning);
                Date_ATD = DateTime.Now;
            }
            return Date_ATD.ToString();
        }
        #endregion
        #region 数据所有权相关方法
        /// <summary>
        /// 列表窗体的权限
        /// </summary>
        /// <param name="pVal"></param>
        /// <param name="CurrentFormEx"></param>
        /// <param name="ObjectType"></param>
        internal static void ChooseFormListAuthority(SAPbouiCOM.Form CurrentFormEx, string ObjectType, ref bool BubbleEvent)
        {
            if (CurrentFormEx.ChooseFromLists.Count <= 0) return;
            var CFL = CurrentFormEx.ChooseFromLists.Item("-1");
            if (CFL.ObjectType == ObjectType)
            {
                IList<int> UserIDs = GetPersons(SAPBoAddon.B1Addon.B1Addon.SBOCompany.UserSignature);
                SAPbouiCOM.Conditions cons = new SAPbouiCOM.Conditions();
                SAPbouiCOM.Condition con = cons.Add();
                if (IsManager(SAPBoAddon.B1Addon.B1Addon.SBOCompany.UserSignature) || IsFinanceUserID())
                {
                    cons = CFL.GetConditions();
                    CFL.SetConditions(cons);
                }
                else
                {
                    #region 用户
                    if (UserIDs.Count > 1)
                        con.BracketOpenNum = 1;
                    con.Alias = "UserSign";
                    con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                    if (UserIDs.Count > 0)
                        con.CondVal = UserIDs[0].ToString();
                    else
                        con.CondVal = "-2";

                    for (int i = 1; i < UserIDs.Count; i++)
                    {
                        con.Relationship = SAPbouiCOM.BoConditionRelationship.cr_OR;
                        con = cons.Add();
                        con.Alias = "UserSign";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        con.CondVal = UserIDs[i].ToString();
                    }
                    if (UserIDs.Count > 1)
                        con.BracketCloseNum = 1;
                    #endregion
                    CFL.SetConditions(cons);
                }
            }
        }
        /// <summary>
        /// 菜单的权限
        /// </summary>
        /// <param name="pVal"></param>
        /// <param name="CurrentFormEx"></param>
        /// <param name="ObjectType"></param>
        /// <param name="BubbleEvent"></param>
        internal static void MenuAuthority(SAPBoAddon.B1AddonBase.B1MenuEvent pVal, SAPbouiCOM.Form CurrentFormEx, string ObjectType, ref bool BubbleEvent)
        {
            //上一条、下一条,//第一条、最后一条
            if (pVal.MenuUID == B1MenuTypes.ado_SYS_Previous || pVal.MenuUID == B1MenuTypes.ado_SYS_Next || pVal.MenuUID == B1MenuTypes.ado_SYS_First || pVal.MenuUID == B1MenuTypes.ado_SYS_Last)
            {
                //判断当前用户是否是管理员
                if (IsManager(SAPBoAddon.B1Addon.B1Addon.SBOCompany.UserSignature))
                {
                    BubbleEvent = true;
                    return;
                }
                //获取当前用户权限的销售员
                IList<int> UserIDs = GetPersons(SAPBoAddon.B1Addon.B1Addon.SBOCompany.UserSignature);
                if (UserIDs.Count()==0)
                {
                    
                }
                //当前值
                string CurrentKey = GetCurrentObjectKey(CurrentFormEx.UniqueID);
                bool NextSalesCode = IsNextBusinessObjectUserID(UserIDs, ObjectType, CurrentKey, pVal.MenuUID);
                if (NextSalesCode == false)
                {
                    BubbleEvent = false;
                    OpenNewBusinessObject(UserIDs, ObjectType, CurrentKey, CurrentFormEx.UniqueID, CurrentFormEx.DataBrowser.BrowseBy, pVal.MenuUID);
                }
                else
                    BubbleEvent = true;
            }

        }
        /// <summary>
        /// 判断当前账户是否是账务的用户
        /// </summary>
        /// <returns></returns>
        internal static bool IsFinanceUserID()
        {
            string SQL = "SELECT top 1 * FROM OUSR Where Department = '1' And UserID = " + SAPBoAddon.B1Addon.B1Addon.SBOCompany.UserSignature.ToString();
            SAPbobsCOM.Recordset rs = SAPBoAddon.B1Addon.B1Addon.SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
            rs.DoQuery(SQL);
            if (rs.RecordCount > 0)
                return true;
            return false;
        }
        /// <summary>
        /// 获取财务账号所拥有的权限
        /// </summary>
        /// <returns></returns>
        internal static IList<int> GetFinanceID()
        {
            IList<int> UserIDs = new List<int>();
            SAPbobsCOM.Recordset rs = SAPBoAddon.B1Addon.B1Addon.SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
            #region 指定用户拥有的权限
            string SQL = @"
                            SELECT T2.UserID,T1.U_UserCode
                            FROM [@AVA_ODRP] T0
	                            INNER JOIN [@AVA_DRP1] T1 ON T0.DocEntry = T1.DocEntry
	                            INNER JOIN OUSR T2 ON T1.U_UserCode = T2.User_Code
	                            INNER JOIN OUSR T3 ON T0.U_UserCode = T3.User_Code
                            Where T3.UserID = {0}
                            ";
            SQL = string.Format(SQL, SAPBoAddon.B1Addon.B1Addon.SBOCompany.UserSignature);
            rs.DoQuery(SQL);
            for (int i = 0; i < rs.RecordCount; i++)
            {
                int userid = rs.Fields.Item("UserID").Value;
                UserIDs.Add(userid);
                rs.MoveNext();
            }
            #endregion

            return UserIDs;
        }
        /// <summary>
        /// 判断用户是不是超级用户
        /// </summary>
        /// <param name="UserSign"></param>
        /// <returns></returns>
        private static bool IsManager(int CurrentUserID)
        {
            string SQL = "SELECT * FROM OUSR Where UserID = {0} And SUPERUSER = 'Y'";
            SQL = String.Format(SQL, CurrentUserID.ToString());
            SAPbobsCOM.Recordset rs = SAPBoAddon.B1Addon.B1Addon.SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
            rs.DoQuery(SQL);
            if (rs.RecordCount > 0)
                return true;
            return false;
        }
        /// <summary>
        /// 判断用户是不是超级用户
        /// </summary>
        /// <param name="UserSign"></param>
        /// <returns></returns>
        internal static bool IsManager()
        {
            string SQL = "SELECT * FROM OUSR Where UserID = {0} And SUPERUSER = 'Y'";
            SQL = String.Format(SQL, SAPBoAddon.B1Addon.B1Addon.SBOCompany.UserSignature.ToString());
            SAPbobsCOM.Recordset rs = SAPBoAddon.B1Addon.B1Addon.SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
            rs.DoQuery(SQL);
            if (rs.RecordCount > 0)
                return true;
            return false;
        }
        /// <summary>
        /// 判断下一条对象是否有权限
        /// </summary>
        /// <param name="UserIDs"></param>
        /// <param name="ObjectKey"></param>
        /// <param name="Command"></param>
        /// <returns></returns>
        private static bool IsNextBusinessObjectUserID(IList<int> UserIDs, string ObjectType, string ObjectKey, string Command)
        {
            if (string.IsNullOrEmpty(ObjectKey)) return false;
            SAPbobsCOM.Recordset rs = GetNextBusinessObjectSQL(Command, ObjectType, ObjectKey);
            if (rs.RecordCount > 0)
            {
                int UserID = rs.Fields.Item("UserSign").Value;
                if (UserIDs.Contains(UserID))
                    return true;
                return false;
            }
            return false;
        }
        /// <summary>
        /// 跳转到新对象
        /// </summary>
        /// <param name="UserIDs"></param>
        /// <param name="ObjectKey"></param>
        /// <param name="FormUID"></param>
        /// <param name="ItemUID"></param>
        /// <param name="Command"></param>
        private static void OpenNewBusinessObject(IList<int> UserIDs, string ObjectType, string ObjectKey, string FormUID, string ItemUID, string Command)
        {
            SAPbobsCOM.Recordset rs;
            string DocEntry = string.Empty;
            if (string.IsNullOrEmpty(ObjectKey))
            {
                if (B1MenuTypes.ado_SYS_Next == Command)
                    Command = B1MenuTypes.ado_SYS_First;
                if (B1MenuTypes.ado_SYS_Previous == Command)
                    Command = B1MenuTypes.ado_SYS_Last;
                rs = GetNextBusinessObjectSQL(Command, UserIDs, ObjectType);
            }
            else
                rs = GetNextBusinessObjectSQL(Command, UserIDs, ObjectType, ObjectKey);
            if (rs.RecordCount <= 0)
            {
                SAPBoAddon.B1Addon.B1Addon.SBOApp.SetStatusBarMessage("您没有浏览其他数据的权限，请与管理员联系进行权限分配。。");
                return;
            }
            DocEntry = rs.Fields.Item("DocEntry").Value.ToString();
            SAPbouiCOM.Form oForm = SAPBoAddon.B1Addon.B1Addon.SBOApp.Forms.Item(FormUID);
            if (oForm.Mode != BoFormMode.fm_FIND_MODE)
                oForm.Mode = SAPbouiCOM.BoFormMode.fm_FIND_MODE;
            oForm.Items.Item(ItemUID).Enabled = true;
            SAPbouiCOM.EditText oEdit = oForm.Items.Item(ItemUID).Specific;
            oEdit.Value = DocEntry;
            oForm.Items.Item("1").Click(SAPbouiCOM.BoCellClickType.ct_Regular);
        }
        /// <summary>
        /// 目标SQL语句
        /// </summary>
        /// <param name="Command"></param>
        /// <param name="UserIDs"></param>
        /// <param name="DocEntry"></param>
        /// <returns></returns>
        private static SAPbobsCOM.Recordset GetNextBusinessObjectSQL(string Command, IList<int> UserIDs, string ObjectType, string DocEntry = null)
        {
            string SQL = string.Empty;
            string TableName = string.Empty;
            SAPbobsCOM.Recordset rs = SAPBoAddon.B1Addon.B1Addon.SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
            TableName = GetBusinessObjectTableName(ObjectType);
            switch (Command)
            {
                case B1MenuTypes.ado_SYS_Next:
                    SQL = @"
							SELECT TOP 1 * 
							FROM (
                                    SELECT Top 1 T0.DocEntry,T0.UserSign,1 OrderID
                                    FROM {0} T0
                                    Where T0.DocEntry >{1} And T0.UserSign in ({2})
									UNION ALL
                                    SELECT Top 1 T0.DocEntry,T0.UserSign,2 OrderID
                                    FROM {0} T0
                                    Where T0.UserSign in ({2})			
							) T0 
                            Order By OrderID";
                    break;
                case B1MenuTypes.ado_SYS_Previous:
                    SQL = @"
								SELECT Top 1 * 
								FROM ( 
                                        SELECT * FROM (
										    SELECT Top 1 T0.DocEntry ,T0.UserSign,1 OrderID
										    FROM {0} T0
										    Where T0.DocEntry < {1} And T0.UserSign in ({2})
                                            Order By DocEntry desc
										) T0
										UNION ALL
                                        SELECT * FROM (
										    SELECT Top 1 T0.DocEntry ,T0.UserSign,2 OrderID
										    FROM {0} T0
										    Where T0.UserSign in ({2})
                                            Order By DocEntry desc
										) T1
								) T0
                                Order By OrderID";
                    break;
                case B1MenuTypes.ado_SYS_First:
                    SQL = @"
                                    SELECT Top 1 T0.DocEntry ,T0.UserSign
                                    FROM {0} T0
                                    Where T0.UserSign in ({2})
                                    Order By T0.DocEntry Asc
                                    ";
                    break;
                case B1MenuTypes.ado_SYS_Last:
                    SQL = @"
                                    SELECT Top 1 T0.DocEntry ,T0.UserSign
                                    FROM {0} T0
                                    Where T0.UserSign in ({2})
                                    Order By T0.DocEntry Desc
                                    ";
                    break;
            }
            string UserIDString = string.Empty;
            foreach (int UserID in UserIDs)
            {
                UserIDString += UserID.ToString() + ",";
            }
            if (UserIDString.Length > 0)
            {
                UserIDString = UserIDString.Substring(0, UserIDString.Length - 1);
            }
            else
                UserIDString = "-2";
            SQL = String.Format(SQL, TableName, DocEntry, UserIDString);
            rs.DoQuery(SQL);
            return rs;
        }
        /// <summary>
        /// 目标SQL语句
        /// </summary>
        /// <param name="Command"></param>
        /// <param name="UserIDs"></param>
        /// <param name="ObjectKey"></param>
        /// <returns></returns>
        private static SAPbobsCOM.Recordset GetNextBusinessObjectSQL(string Command, string ObjectType, string ObjectKey)
        {
            string SQL = string.Empty;
            string TableName = string.Empty;
            SAPbobsCOM.Recordset rs = SAPBoAddon.B1Addon.B1Addon.SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
            TableName = GetBusinessObjectTableName(ObjectType);
            //if (ObjectType == "")
            //{ 

            //}
            #region
            switch (Command)
            {
                case B1MenuTypes.ado_SYS_Next:
                    SQL = @"
                                    SELECT Top 1 T0.DocEntry,T0.UserSign
                                    FROM {0} T0
                                    Where T0.DocEntry > {1}";

                    break;
                case B1MenuTypes.ado_SYS_Previous:
                    SQL = @"
                                    SELECT Top 1 T0.DocEntry ,T0.UserSign
                                    FROM {0} T0
                                    Where T0.DocEntry < {1}";

                    break;
                case B1MenuTypes.ado_SYS_First:
                    SQL = @"
                                    SELECT Top 1 T0.DocEntry ,T0.UserSign
                                    FROM {0} T0
                                    Order By T0.DocEntry Asc";
                    break;
                case B1MenuTypes.ado_SYS_Last:
                    SQL = @"
                                    SELECT Top 1 T0.DocEntry ,T0.UserSign
                                    FROM {0} T0
                                    Order By T0.DocEntry Desc";
                    break;
            }
            #endregion
            SQL = String.Format(SQL, TableName, ObjectKey);
            rs.DoQuery(SQL);
            return rs;
        }
        /// <summary>
        /// 获取业务对象的表名
        /// </summary>
        /// <param name="ObjectType"></param>
        /// <returns></returns>
        private static string GetBusinessObjectTableName(string ObjectType)
        {
            string SQL = String.Empty;
            SAPbobsCOM.Recordset rs = SAPBoAddon.B1Addon.B1Addon.SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
            SQL = "SELECT '[@'+ TableName +']' TableName FROM OUDO Where Code = '" + ObjectType + "'";
            rs.DoQuery(SQL);
            return rs.Fields.Item("TableName").Value;
        }
        /// <summary>
        /// 获取当前用户所有拥有的权限的账户
        /// </summary>
        /// <param name="UserID"></param>
        /// <returns></returns>
        private static IList<int> GetPersons(int CurrentUserID)
        {
            IList<int> UserIDs = new List<int>();
            string SQL = @"
                                    SELECT T0.UserID,T1.SalesPrson,T2.role,T3.teamID,t3.descriptio,T3.U_FatherID,T3.U_IsShare
                                    FROM OUSR T0
	                                    INNER JOIN OHEM T1 ON T0.USERID = T1.userId
	                                    INNER JOIN HTM1 T2 ON T1.empID = T2.empID
	                                    INNER JOIN OHTM T3 ON T2.teamID = T3.teamID
                                    Where T0.UserID = {0}
                                    ";
            SAPbobsCOM.Recordset rs = SAPBoAddon.B1Addon.B1Addon.SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
            SQL = string.Format(SQL, CurrentUserID);
            rs.DoQuery(SQL);
            if (rs.RecordCount > 0)
            {
                //当前用户
                int usercode = CurrentUserID;
                //当前用户所在的团队
                string tempID = rs.Fields.Item("descriptio").Value;
                //当前团队是否共享
                string IsShare = rs.Fields.Item("U_IsShare").Value;
                if (UserIDs.Contains(usercode) == false)
                    UserIDs.Add(usercode);
                #region 当前用户是否是领导，如果是则可以查看下级
                //if (rs.Fields.Item("role").Value == "L")
                //{
                SQL = @"
                                SELECT T0.UserID,T0.User_Code,T0.U_Name,T1.SalesPrson,T2.role,T3.teamID,t3.descriptio,T3.U_FatherID
                                FROM OUSR T0
	                                INNER JOIN OHEM T1 ON T0.USERID = T1.userId
	                                INNER JOIN HTM1 T2 ON T1.empID = T2.empID
	                                INNER JOIN OHTM T3 ON T2.teamID = T3.teamID
                                Where cast(T3.descriptio as nvarchar(30)) = '{0}' And T0.UserID <> {1}
                                ";
                SQL = string.Format(SQL, tempID, rs.Fields.Item("UserID").Value);
                rs.DoQuery(SQL);
                for (int i = 0; i < rs.RecordCount; i++)
                {
                    usercode = rs.Fields.Item("UserID").Value;
                    if (UserIDs.Contains(usercode) == false)
                        UserIDs.Add(usercode);
                    rs.MoveNext();
                }
                IList<string> UseTeams = new List<string>();
                //获取当前团队下的所有团队
                GetTeam(UseTeams, tempID);
                foreach (string team in UseTeams)
                {
                    SQL = @"
                                SELECT T0.UserID,T0.User_Code,T0.U_Name,T1.SalesPrson,T2.role,T3.teamID,t3.descriptio,T3.U_FatherID
                                FROM OUSR T0
	                                INNER JOIN OHEM T1 ON T0.USERID = T1.userId
	                                INNER JOIN HTM1 T2 ON T1.empID = T2.empID
	                                INNER JOIN OHTM T3 ON T2.teamID = T3.teamID
                                Where cast(T3.descriptio as nvarchar(30)) = '{0}'
                                ";
                    SQL = string.Format(SQL, team);
                    rs.DoQuery(SQL);
                    for (int i = 0; i < rs.RecordCount; i++)
                    {
                        usercode = rs.Fields.Item("UserID").Value;
                        if (UserIDs.Contains(usercode) == false)
                            UserIDs.Add(usercode);
                        rs.MoveNext();
                    }
                }
                //}
                #endregion
                #region 团队内权限是否可以共享
                //else
                //{
                if (IsShare == "Y")
                {
                    SQL = @"
                                SELECT T0.UserID,T0.User_Code,T0.U_Name,T1.SalesPrson,T2.role,T3.teamID,t3.descriptio,T3.U_FatherID
                                FROM OUSR T0
	                                INNER JOIN OHEM T1 ON T0.USERID = T1.userId
	                                INNER JOIN HTM1 T2 ON T1.empID = T2.empID
	                                INNER JOIN OHTM T3 ON T2.teamID = T3.teamID
                                Where T0.UserID <> {1} And cast(T3.descriptio as nvarchar(30)) = '{0}'
                                ";
                    SQL = string.Format(SQL, tempID, CurrentUserID);
                    rs.DoQuery(SQL);
                    for (int i = 0; i < rs.RecordCount; i++)
                    {
                        usercode = rs.Fields.Item("UserID").Value;
                        if (UserIDs.Contains(usercode) == false)
                            UserIDs.Add(usercode);
                        rs.MoveNext();
                    }
                }
                //}
                #endregion
                #region 指定用户拥有的权限
                SQL = @"
                            SELECT T3.UserID,T0.U_UserCode
                            FROM [@AVA_ODRP] T0
	                            INNER JOIN [@AVA_DRP1] T1 ON T0.DocEntry = T1.DocEntry
	                            INNER JOIN OUSR T2 ON T1.U_UserCode = T2.User_Code
	                            INNER JOIN OUSR T3 ON T0.U_UserCode = T3.User_Code
                            Where T2.UserID = {0}
                            ";
                SQL = string.Format(SQL, CurrentUserID);
                rs.DoQuery(SQL);
                for (int i = 0; i < rs.RecordCount; i++)
                {
                    usercode = rs.Fields.Item("UserID").Value;
                    if (UserIDs.Contains(usercode) == false)
                        UserIDs.Add(usercode);
                    rs.MoveNext();
                }
                #endregion
                #region 财务权限
                SQL = @"
                             SELECT T2.UserID,T2.User_Code
                            FROM [@AVA_ODRP] T0
	                            INNER JOIN [@AVA_DRP1] T1 ON T0.DocEntry = T1.DocEntry
	                            INNER JOIN OUSR T2 ON T1.U_UserCode = T2.User_Code
	                            INNER JOIN OUSR T3 ON T0.U_UserCode = T3.User_Code
                            Where T3.UserID ={0} AND T3.Department=1
                            ";
                SQL = string.Format(SQL, CurrentUserID);
                rs.DoQuery(SQL);
                for (int i = 0; i < rs.RecordCount; i++)
                {
                    usercode = rs.Fields.Item("UserID").Value;
                    if (UserIDs.Contains(usercode) == false)
                        UserIDs.Add(usercode);
                    rs.MoveNext();
                }
                #endregion
            }
            return UserIDs;
        }
        /// <summary>
        /// 获取当前用户所有拥有的权限的账户
        /// </summary>
        /// <param name="UserID"></param>
        /// <returns></returns>
        internal static IList<int> GetPersons()
        {
            return GetPersons(SAPBoAddon.B1Addon.B1Addon.SBOCompany.UserSignature);
        }
        /// <summary>
        /// 获取当前用户所有拥有的团队
        /// </summary>
        /// <param name="UseTeam"></param>
        /// <param name="GroupID"></param>
        private static void GetTeam(IList<string> UseTeam, string GroupID)
        {
            string SQL = "SELECT descriptio FROM OHTM T0 Where T0.U_FatherID = '{0}'";
            SQL = string.Format(SQL, GroupID);
            SAPbobsCOM.Recordset rs = SAPBoAddon.B1Addon.B1Addon.SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
            rs.DoQuery(SQL);
            for (int i = 0; i < rs.RecordCount; i++)
            {
                string teamID = rs.Fields.Item("descriptio").Value;
                UseTeam.Add(teamID);
                GetTeam(UseTeam, teamID);
                rs.MoveNext();
            }
        }
        /// <summary>
        /// 获取当前对象的关键值
        /// </summary>
        /// <param name="FormUID"></param>
        /// <returns></returns>
        private static string GetCurrentObjectKey(string FormUID)
        {
            SAPbouiCOM.Form oForm = SAPBoAddon.B1Addon.B1Addon.SBOApp.Forms.Item(FormUID);
            string ItemUID = oForm.DataBrowser.BrowseBy;
            oForm.Items.Item(ItemUID).Enabled = true;
            SAPbouiCOM.EditText oEdit = oForm.Items.Item(ItemUID).Specific;
            return oEdit.Value;
        }
        #endregion

    }

    internal enum FormType_PackType
    {
        /// <summary>
        /// 进口报关
        /// </summary>
        OCTC_UID = 0,
        /// <summary>
        /// 出口报关
        /// </summary>
        OATC_UID = 1,
        /// <summary>
        /// 到港
        /// </summary>
        OARP_UID = 2,
    }

    /// <summary>
    /// 分单发货、收货
    /// </summary>
    internal enum IssueOrReceipt
    {
        Issue,
        Receipt
    }
    /// <summary>
    /// 把阿拉伯数字转换成英文数字的工具类
    /// </summary>
    /// <author>Webb.Wen</author>
    /// <create>2012-03-20 14:51:11</create>
    public class Arabic2Engish
    {
        private string[] StrNO = new string[19];
        private string[] Unit = new string[8];
        private string[] StrTens = new string[9];

        #region NumberToString
        public string NumberToString(double Number)
        {
            if (Math.Round(Number, 2) == 0.0d)
            {
                return "ZERO";
            }
            string Str;
            string BeforePoint;
            string AfterPoint;
            string tmpStr;
            int nBit;
            string CurString;
            int nNumLen;
            Init();
            Str = Convert.ToString(Math.Round(Number, 2));
            if (Str.IndexOf(".") == -1)
            {
                BeforePoint = Str;
                AfterPoint = "";
            }
            else
            {
                BeforePoint = Str.Substring(0, Str.IndexOf("."));
                AfterPoint = Str.Substring(Str.IndexOf(".") + 1, Str.Length - Str.IndexOf(".") - 1);
            }
            if (BeforePoint.Length > 12)
            {
                return null;
            }
            Str = "";
            while (BeforePoint.Length > 0)
            {
                nNumLen = Len(BeforePoint);
                if (nNumLen % 3 == 0)
                {
                    CurString = Left(BeforePoint, 3);
                    BeforePoint = Right(BeforePoint, nNumLen - 3);
                }
                else
                {
                    CurString = Left(BeforePoint, (nNumLen % 3));
                    BeforePoint = Right(BeforePoint, nNumLen - (nNumLen % 3));
                }
                nBit = Len(BeforePoint) / 3;
                tmpStr = DecodeHundred(CurString);
                if ((BeforePoint == Len(BeforePoint).ToString() || nBit == 0) && Len(CurString) == 3)
                {
                    if (System.Convert.ToInt32(Left(CurString, 1)) != 0 & System.Convert.ToInt32(Right(CurString, 2)) != 0)
                    {
                        tmpStr = Left(tmpStr, tmpStr.IndexOf(Unit[3]) + Len(Unit[3])) + Unit[7] + " " + Right(tmpStr, Len(tmpStr) - (tmpStr.IndexOf(Unit[3]) + Len(Unit[3])));
                    }
                    else
                    {
                        tmpStr = Unit[7] + " " + tmpStr;
                    }
                }
                if (nBit == 0)
                {
                    Str = Convert.ToString(Str + " " + tmpStr).Trim();
                }
                else
                {
                    Str = Convert.ToString(Str + " " + tmpStr + " " + Unit[nBit - 1]).Trim();
                }
                if (Left(Str, 3) == Unit[7])
                {
                    Str = Convert.ToString(Right(Str, Len(Str) - 3)).Trim();
                }
                if (BeforePoint == Len(BeforePoint).ToString())
                {
                    return "";
                }
            }
            BeforePoint = Str;
            if (Len(AfterPoint) > 0)
            {
                AfterPoint = " " + Unit[5] + " " + DecodeHundred(AfterPoint) + " " + Unit[6];
            }
            else
            {
                AfterPoint = "";// Unit[4];
            }
            return BeforePoint + AfterPoint;

        }

        #endregion

        #region Init
        private void Init()
        {
            if (StrNO[0] != "ONE")
            {
                StrNO[0] = "ONE";
                StrNO[1] = "TWO";
                StrNO[2] = "THREE";
                StrNO[3] = "FOUR";
                StrNO[4] = "FIVE";
                StrNO[5] = "SIX";
                StrNO[6] = "SEVEN";
                StrNO[7] = "EIGHT";
                StrNO[8] = "NINE";
                StrNO[9] = "TEN";
                StrNO[10] = "ELEVEN";
                StrNO[11] = "TWELVE";
                StrNO[12] = "THIRTEEN";
                StrNO[13] = "FOURTEEN";
                StrNO[14] = "FIFTEEN";
                StrNO[15] = "SIXTEEN";
                StrNO[16] = "SEVENTEEN";
                StrNO[17] = "EIGHTEEN";
                StrNO[18] = "NINETEEN";
                StrTens[0] = "TEN";
                StrTens[1] = "TWENTY";
                StrTens[2] = "THIRTY";
                StrTens[3] = "FORTY";
                StrTens[4] = "FIFTY";
                StrTens[5] = "SIXTY";
                StrTens[6] = "SEVENTY";
                StrTens[7] = "EIGHTY";
                StrTens[8] = "NINETY";
                Unit[0] = "THOUSAND";
                Unit[1] = "MILLION";
                Unit[2] = "BILLION";
                Unit[3] = "HUNDRED";
                Unit[4] = "ONLY";
                Unit[5] = "POINT";
                Unit[6] = "CENT";
                Unit[7] = " AND";
            }
        }

        #endregion

        #region DecodeHundred
        private string DecodeHundred(string HundredString)
        {
            int tmp;
            string rtn = "";
            if (Len(HundredString) > 0 && Len(HundredString) <= 3)
            {
                switch (Len(HundredString))
                {
                    case 1:
                        tmp = System.Convert.ToInt32(HundredString);
                        if (tmp != 0)
                        {
                            rtn = StrNO[tmp - 1].ToString();
                        }
                        break;
                    case 2:
                        tmp = System.Convert.ToInt32(HundredString);
                        if (tmp != 0)
                        {
                            if ((tmp < 20))
                            {
                                rtn = StrNO[tmp - 1].ToString();
                            }
                            else
                            {
                                if (System.Convert.ToInt32(Right(HundredString, 1)) == 0)
                                {
                                    rtn = StrTens[Convert.ToInt32(tmp / 10) - 1].ToString();
                                }
                                else
                                {
                                    rtn = Convert.ToString(StrTens[Convert.ToInt32(tmp / 10) - 1] + "-" + StrNO[System.Convert.ToInt32(Right(HundredString, 1)) - 1]);
                                }
                            }
                        }
                        break;
                    case 3:
                        if (System.Convert.ToInt32(Left(HundredString, 1)) != 0)
                        {
                            rtn = Convert.ToString(StrNO[System.Convert.ToInt32(Left(HundredString, 1)) - 1] + " " + Unit[3] + " " + DecodeHundred(Right(HundredString, 2)));
                        }
                        else
                        {
                            rtn = DecodeHundred(Right(HundredString, 2)).ToString();
                        }
                        break;
                    default:
                        break;
                }
            }
            return rtn;
        }

        #endregion

        #region Left
        private string Left(string str, int n)
        {
            return str.Substring(0, n);
        }
        #endregion

        #region Right
        private string Right(string str, int n)
        {
            return str.Substring(str.Length - n, n);
        }
        #endregion

        #region Len
        private int Len(string str)
        {
            return str.Length;
        }
        #endregion
    }
}